如何在django中下载文件

时间:2018-01-24 05:40:48

标签: django django-models django-templates django-views

我上传了一些存储在/ media / documents中的文件。我还在settings.py中设置了MEDIA_URL和MEDIA_ROOT,并在urls.py中提供了相应的url。 文件通过表单上传,现在我需要下载上传的文件。 我对如何从浏览器下载感到困惑。有人可以帮助我,我是django的新手。

模型

class Document(models.Model):
    description = models.CharField(max_length=255, blank=False)
    document = models.FileField(upload_to='documents/')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    is_diagnoised = models.BooleanField(default=False)
    uploaded_by = models.CharField(max_length=20, default="")
    downloaded_by = models.CharField(max_length=20, default="")`

views.py

def index(request):
if request.user.is_authenticated:
    uid = request.user.id
    usern = request.user.username
    if Profile.objects.filter(role='Doctor', id=uid):#file upload
        if request.method == 'POST':
            form = DocumentForm(request.POST, request.FILES)
            if form.is_valid():
                post = form.save(commit=False)
                post.uploaded_by = usern
                post.save()
                return redirect('index')
        else:
            form = DocumentForm()
            no_diagno = Document.objects.filter(is_diagnoised=False, uploaded_by=usern)
            is_diagno = Document.objects.filter(is_diagnoised=True, uploaded_by=usern)
            context = {
                'ndg':no_diagno,
                'ydg':is_diagno,
                'form': form
            }
        return render(request, 'upload.html', context)

    else:#file download
        if request.method == 'POST':
            form = RadioForm(request.POST, request.FILES)
            if form.is_valid():
                post = form.save(commit=False)
                post.downloaded_by = usern
                post.is_diagnoised = 'True'
                post.save()
                return redirect('index')
        if request.method == 'GET':
            form = RadioForm()
            no_diagno = Document.objects.filter(is_diagnoised=False)
            is_diagno = Document.objects.filter(is_diagnoised=True)
            context = {
                'ndg':no_diagno,
                'ydg':is_diagno,
                'form': form
            }
        return render(request, 'index-rad.html', context)

def download(request, path):
    file_path = os.path.join(settings.MEDIA_ROOT, media/documents)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
            response = HttpResponse(fh.read())
            response['Content-Disposition'] = 'inline; filename=' +os.path.basename(file_path)
            return response
    raise Http404

索引rad.html

{% for n in ndg %}
<ol>
<li>{{n.description}} <a href="{% url 'download' %}">download</a></li>
</ol>
{% endfor %}

1 个答案:

答案 0 :(得分:0)

问题不是很有用,但是当我不知道时,你需要在你的teplate中提供文件的URL。为此,您只需使用{{myfile.url}}。