138π
You missed underscore in argument document_root. But itβs bad idea to use serve
in production. Use something like this instead:
import os
from django.conf import settings
from django.http import HttpResponse, Http404
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
66π
You can add βdownloadβ attribute inside your tag to download files.
<a href="/project/download" download> Download Document </a>
- [Django]-How to set current user to user field in Django Rest Framework?
- [Django]-Django Forms: if not valid, show form with error message
- [Django]-Django override save for model only in some cases?
42π
In view.py Implement function like,
def download(request, id):
obj = your_model_name.objects.get(id=id)
filename = obj.model_attribute_name.path
response = FileResponse(open(filename, 'rb'))
return response
- [Django]-Visual Studio Code: Intellisense not working
- [Django]-Django add extra field to a ModelForm generated from a Model
- [Django]-VueJS + Django Channels
8π
When you upload a file using FileField
, the file will have a URL that you can use to point to the file and use HTML download
attribute to download that file you can simply do this.
models.py
The model.py looks like this
class CsvFile(models.Model):
csv_file = models.FileField(upload_to='documents')
views.py
#csv upload
class CsvUploadView(generic.CreateView):
model = CsvFile
fields = ['csv_file']
template_name = 'upload.html'
#csv download
class CsvDownloadView(generic.ListView):
model = CsvFile
fields = ['csv_file']
template_name = 'download.html'
Then in your templates.
#Upload template
upload.html
<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>
#download template
download.html
{% for document in object_list %}
<a href="{{ document.csv_file.url }}" download class="btn btn-dark float-right">Download</a>
{% endfor %}
I did not use forms, just rendered model but either way, FileField is there and it will work the same.
- [Django]-Django QuerySet order
- [Django]-Django admin, hide a model
- [Django]-Add additional options to Django form select widget
4π
Iβve found Djangoβs FileField
to be really helpful for letting users upload and download files. The Django documentation has a section on managing files. You can store some information about the file in a table, along with a FileField
that points to the file itself. Then you can list the available files by searching the table.
- [Django]-How to write setup.py to include a Git repository as a dependency
- [Django]-Django.db.migrations.exceptions.InconsistentMigrationHistory
- [Django]-"gettext()" vs "gettext_lazy()" in Django
3π
-
<a href='/your-download-view/' download>Download</a>
-
In your view:
from django.http import FileResponse
def download(request):
# pre-processing, authorizations, etc.
# ...
return FileResponse(open(path_to_file, 'rb'), as_attachment=True)
- [Django]-Extend base.html problem
- [Django]-Django @login_required decorator for a superuser
- [Django]-Best practices for adding .gitignore file for Python projects?
2π
@Biswadpβs solution worked greatly for me
In your static folder, make sure to have the desired files you would like the user to download
In your HTML template, your code should look like this :
<a href="{% static 'Highlight.docx' %}"> Download </a>
- [Django]-How to convert a Django QuerySet to a list?
- [Django]-Pytest.mark.parametrize with django.test.SimpleTestCase
- [Django]-How to set current user to user field in Django Rest Framework?
2π
Using the below approach makes everything less secure since any user can access any userβs file.
<a href="/project/download" download> Download Document </a>
Using the below approach makes no sense since Django only handles one requests at the time (unless you are using gunicorn or something else), and believe me, the below approach takes a lot of time to complete.
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
So what is the optimum solution?
Use Nginx authenticated routes. When requesting a file from Nginx you can make a request to a route and depending on the HTTP response Nginx allows to denies that request. This makes it very secure and also scalable and performant.
You can ready about more here
- [Django]-Django Query __isnull=True or = None
- [Django]-Redirect / return to same (previous) page in Django?
- [Django]-Bypass confirmation prompt for pip uninstall
2π
import mimetypes
from django.http import HttpResponse, Http404
mime_type, _ = mimetypes.guess_type(json_file_path)
if os.path.exists(json_file_path):
with open(json_file_path, 'r') as fh:
response = HttpResponse(fh, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % 'config.json'
return response
raise Http404
- [Django]-POST jQuery array to Django
- [Django]-Django 1.5b1: executing django-admin.py causes "No module named settings" error
- [Django]-Django add extra field to a ModelForm generated from a Model
1π
Simple using html like this downloads the file mentioned using static keyword
<a href="{% static 'bt.docx' %}" class="btn btn-secondary px-4 py-2 btn-sm">Download CV</a>
- [Django]-How to add clickable links to a field in Django admin?
- [Django]-How to iterate through dictionary in a dictionary in django template?
- [Django]-What is the easiest way to clear a database from the CLI with manage.py in Django?
1π
1.settings.py:
MEDIA_DIR = os.path.join(BASE_DIR,'media')
#Media
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
2.urls.py:
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
3.in template:
<a href="{{ file.url }}" download>Download File.</a>
Work and test in django >=3
for more detail use this link:
https://youtu.be/MpDZ34mEJ5Y
- [Django]-In django, how do I sort a model on a field and then get the last item?
- [Django]-How to concatenate strings in django templates?
- [Django]-Django: Arbitrary number of unnamed urls.py parameters
1π
If the file is a FileField in the model, this is the way I do it:
try:
download_file = PrintingFile.objects.get(pk=kwargs.get('pk_file', 0))
return FileResponse(download_file.file.open(), as_attachment=True)
except PrintingFile.DoesNotExist:
raise Http404
More here
- [Django]-Django SUM Query?
- [Django]-Django py.test does not find settings module
- [Django]-In django do models have a default timestamp field?
0π
I use this method:
{% if quote.myfile %}
<div class="">
<a role="button"
href="{{ quote.myfile.url }}"
download="{{ quote.myfile.url }}"
class="btn btn-light text-dark ml-0">
Download attachment
</a>
</div>
{% endif %}
- [Django]-Django Footer and header on each page with {% extends }
- [Django]-What the difference between using Django redirect and HttpResponseRedirect?
- [Django]-Manage.py runserver
0π
If you hafe upload your file in media than:
media
example-input-file.txt
views.py
def download_csv(request):
file_path = os.path.join(settings.MEDIA_ROOT, 'example-input-file.txt')
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
urls.py
path('download_csv/', views.download_csv, name='download_csv'),
download.html
a href="{% url 'download_csv' %}" download=""
- [Django]-Does django with mongodb make migrations a thing of the past?
- [Django]-How to make Django serve static files with Gunicorn?
- [Django]-Django, ModelChoiceField() and initial value