1

This is my model

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

This is my view to upload.

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
})

I'd like to write a view function for lecturer to download those files with upload assignment primary key. Any one have any idea?

mbdow
  • 43
  • 7

1 Answers1

0

Based on similar questions (this and this) and the docs you could try:

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

Content types and file extensions are always a tricky part with user-submitted files, since there are a lot of thinks that could go wrong or be attack vectors. Read more: django user-uploaded-content-security.

You could also look into the special FileResponse class.

Ralf
  • 16,086
  • 4
  • 44
  • 68