0

I am working on a Final Project for CS50W and I want a small app that allows users to upload their 'scripts' - files that are either .doc or .docx. These files are then saved in a separate folder and its url is saved in a models field.

I want to create a separate view for displaying the contents of these files, that I can then later on style separately (changing background and text colors, size, etc.), so I want to extract the text from these files and pass it on to my template. But when I do that with open file function, I get FileNotFoundError - which I presume is because this file is not .txt file.

What would be the best way to achieve this?

Here's the relevant part of my code:

class Script(models.Model):
...
    upload = models.FileField("Select your script", upload_to="scripts/%Y/%m/%D/", validators=[FileExtensionValidator(allowed_extensions=['doc', 'docx'])])
...

def read(request, script_id):
    script = Script.objects.get(pk=script_id)
    file = open(script.upload.url, 'r')
    content = file.read()
    file.close()
    return render(request, 'astator/read.html', {
        'script':script,
        'content':content,
    })

Maybe there's also a better way to achieve this with JS? Anyhow, thanks in advance for your help!

0 Answers0