Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

django - How can I download the file linked with the post?

I'm quite new to using Django and I am trying to develop a website where the user can download file at the end of the post. Post model:

class Article(models.Model):
    title = models.CharField(max_length=30)
    content = models.TextField()
    pub_date = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    file = models.FileField(upload_to='code_files/')


    def __str__(self):
        return self.title

I have a views:

def download(request):
    response = HttpResponse(open(f"media/code_files/tests.py", 'rb').read())
    response['Content-Type'] = 'text/plain'
    response['Content-Disposition'] = f'attachment; filename=tests.py'
    return response

How can I download the file linked with the post?

question from:https://stackoverflow.com/questions/65851983/how-can-i-download-the-file-linked-with-the-post

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From Dajngo docs FileResponse is a subclass of StreamingHttpResponse optimized for binary files.

import os

from django.http import FileResponse
from django.views.decorators.http import require_POST

@require_POST    
def download(request):
    article = Article.objects.get(id=1)
    fullpath = article.file.path
    if not os.path.exists(fullpath):
        raise Http404('{0} does not exist'.format(fullpath))
    return FileResponse(
        open(fullpath, 'rb'), as_attachment=True,
        filename=article.file.name)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...