如何在Django中下载文件

时间:2018-05-07 22:55:41

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

这是我的模特

class UploadAssignment(models.Model):
    doc=models.FileField()
    assignment = models.ForeignKey(AssignAssignment, on_delete=models.CASCADE)
    student= models.ForeignKey(Student, on_delete=models.CASCADE)

这是我上传的观点。

def upload_assignment(request,pk):
student = get_object_or_404(Student,user_id=request.user)
assign = get_object_or_404(AssignAssignment, pk=pk)
if request.method == 'POST':
    form = AssignmentUpload(request.POST, request.FILES)
    if form.is_valid():
        m=form.save(commit=False)
        m.student_id=student.user_id
        m.assignment_id=assign.pk
        print(m)
        m.save()
        messages.success(request, 'Assignment upload is successful')
        return redirect('home')
else:
    form = AssignmentUpload()
return render(request, 'accounts/students/uploadassignments.html', {
    'form': form
})

我想为讲师编写一个视图函数来下载带有上传分配主键的文件。有人有任何想法吗?

1 个答案:

答案 0 :(得分:0)

基于类似的问题(thisthis)以及您可以尝试的docs

def download_file(request, pk):
    obj = get_object_or_404(UploadAssignment, pk=pk)

    response = HttpResponse(
        obj.doc,
        content_type='application/whatever-the-correct-type-is')
    response['Content-Disposition'] = 'attachment; filename="foo.xls"'
    return response

内容类型和文件扩展名对于用户提交的文件来说总是很棘手,因为有很多想法可能会出错或者是攻击媒介。 阅读更多:django user-uploaded-content-security

您还可以查看特殊的FileResponse类。