Uploaded file type check in django

I want to design a form in django that takes a text file as input and does some processing using it.

I have written the following HTML file.

<!DOCTYPE html>
<html>
    <body>
        <h1>Transcript To Voiceover Convertor</h1><br/>
        <form action="" enctype="multipart/form-data" method="POST">
            {% csrf_token %}
            <label for="document"> <b> Select a text file: </b> </label> <br/>
            <input type="file" name="document"> <br/><br/><br/>
            <!--<input type="file" accept="text/*" name="document"> <br/><br/><br/>-->
            <b> Select a gender for the voiceover </b>
            <br/>
            {{ form }}
            <br/><br/><br/><br/>
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

As you can see, one of the input line is uncommented and the other one is commented. So basically, in the commented line I tried to use the accept attribute with text MIME but the problem I am facing is that in this case the browser only detects files with .txt extension but in Operating system like Ubuntu/Linux it is not necessary for text files to have .txt extension. So when I am using the commented line for input it is not able to detect those files. So, can someone please suggest me what should I do?

My second problem is related to the first one. So, as you must be knowing that having a check on the client side does not make much sense as it can be easily bypassed so can someone please suggest me what changes should I do to my views.py file which is basically my backend.

Here is my views.py file.

from django.shortcuts import render
from django.http import HttpResponse
from subprocess import run
from django.core.files.storage import FileSystemStorage
from .models import Transcript
from tutorial.forms import TranscriptForm

# Create your views here.

def audio(request):
    if request.method == 'POST':
        form = TranscriptForm(request.POST)
        uploaded_file = request.FILES["document"]
        file_name = uploaded_file.name
        fs = FileSystemStorage()
        name = fs.save(file_name, uploaded_file)
        if form.is_valid():
            run(["gnome-terminal", "--", "sh", "-c", f"espeak -ven+{request.POST['gender']}1 -f {name} -w {name}_audio"], cwd="media/")
            audio_name = name+"_audio"
            context = {'generated_audio': audio_name, 'original_name': file_name}
            return render(request, 'DownloadAudio.html', context)
        else:
            return HttpResponse("Something went wrong. Please try again later.")
    context = {'form': TranscriptForm()}
    return render(request, 'upload.html', context)

I have read I can use MIME type but I am not sure how to do it.

I am new to django and some help will be apreciated.

Back to Top