Download file stored in a model with FileField using Django

I'm planning on creating a simple file upload application in Django (incorporated in some bigger project). For this one, I'm using two links: /files/ - to list all the uploaded files from a specific user, and /files/upload/ - to display the upload form for the user to add a new file on the server.

I'm using a PostgreSQL database, and I'm planning to store all my files in a File model, that looks like this:

class File(models.Model):
    content = models.FileField()
    uploader = models.ForeignKey(User, on_delete=models.CASCADE)

My file upload view looks like this:

@login_required
def file_upload_view(request):
    if request.method == "POST" and request.FILES['file']:
        file = request.FILES['file']
        File.objects.create(content=file, uploader=request.user)
        return render(request, "file_upload_view.html")
    else:
        return render(request, "file_upload_view.html")

while my file list view looks like this:

@login_required
def file_view(request):
    files = File.objects.filter(uploader = request.user)
    return render(request, "file_view.html", {'files': files})

The problem is, I want my file_view() to display all files uploaded by a certain user in a template (which I already did), each file having a hyperlink to its download location. I've been trying to do this in my file list template:

{% extends 'base.html' %}
{% block content %}
<h2>Files of {{ request.user }}</h2>
<br>
{% for file in files %}
    <a href="{{ file.content }}" download>{{ file.content }}</a>
{% endfor %}
{% endblock %}

but my browser is trying to download some .htm page, even if the file I've uploaded is of type .txt.

My question is: do I also need to upload the file in a certain directory, before adding it to the model? Do I need to actually add the file's URL as a new field in my model? Aren't the files automatically uploaded to my PostgreSQL database?

Any help would be greatly appreciated. Thank you.

I guess you should show a folder to where you want to save your files like this: content = models.FileField(upload_to='/myfiles/'). And then you can show the url ("{% url 'file.url' %}") in your html because the database actually saves the url of your file and stores the file itself in the folder you've showed in your model.

Back to Top