Download an uploaded django .docx file

Viewed 41

I have a website where i upload a .docx file and then the users can download the document.

my model

    class Files(model.Model):
      name = models.CharField(max_length=200)
      doc_File = models.FileField(upload_to='media')

my View

    def Uploaded(request):
      file = Files.objects.filter('doc_File')  
      return render(request, 'uploaded_files.html', {'file':file})

urls

    path('file, views.Uploaded, name='file'),    

my html page

{% block content %}

    <h4>Download Document Below</h4>
     {% for f in file %}
    <a href="{% url 'f.url' %}" Download>{{f.url}}</a>
     {% endfor %}
{% endblock %}

I am not able to download the .docx file could anyone help pliz ....

1 Answers

Youre return is not right, try

data = open(doc.name, "rb").read() //doc.name is youre filefield from your model
return HttpResponse(data, content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")

In template:

 <a href="{%  url "//youre url in url.py to the download view" %}>
Related