Django 返回下载并重定向到其他页面



我正在设置一个站点,作为用户,我可以将某些内容分配给某人,并且每当分配新的PDF文档时都会创建一个新的PDF文档。目前,用户只需转到用户帐户页面,单击分配页面,然后填写表单。提交此表单后,将创建一个文档(pdf(并将其与创建的模型一起保存,并将用户重定向到他们刚刚访问的帐户页面。在这里,他们可以单击已分配的内容以下载创建的文档。但是,我希望提交后它们会被重定向回帐户页面并开始下载。我正在考虑只是使用请求发出获取请求,但我读到这不是一个好方法。以下是我下载的代码以及视图提交的代码。

下载视图

@login_required
def attendance_download(request, employee_id, attendance_id):
employee = Employee.objects.get(employee_id=employee_id)
attendance = Attendance.objects.get(id=attendance_id)
pretty_filename = f'{employee.first_name} {employee.last_name} Attendance Point.pdf'
try:
with open(attendance.document.path, 'rb') as f:
response = HttpResponse(f, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = f'attachment;filename="{pretty_filename}"'
return response
except:
messages.add_message(request, messages.ERROR, 'No File to Download')
return redirect('employee-account', employee_id)

表单视图

employee = Employee.objects.get(employee_id=employee_id)
if request.method == 'GET':
a_form = AssignAttendance()
data = {
'a_form': a_form,
'employee': employee
}
return render(request, 'employees/assign_attendance.html', data)
else:
a_form = AssignAttendance(request.POST)
if a_form.is_valid():
employee_name = f'{employee.first_name} {employee.last_name}'
incident_date = a_form.cleaned_data['incident_date'].strftime('%m-%d-%Y')
reason = a_form.cleaned_data['reason']
reported_by = f'{request.user.first_name} {request.user.last_name}'
# This has been ordered to match the document
history = {
'0': 0,
'6': 0,
'7': 0,
'2': 0,
'4': 0,
'5': 0,
'3': 0,
}
exemption = a_form.cleaned_data['exemption']
attendance_records = Attendance.objects.filter(employee=employee)
# Goes through each of the past attendance points and adds +1 to the history ignoring '1'(Consecutive) and
# treating '8'(Late Lunch) as '6'(< 15min)
for attendance_record in attendance_records:
if attendance_record.reason != '1':
if attendance_record.reason == '8':
history['6'] += 1
else:
history[attendance_record.reason] += 1
counseling = counseling_required(employee, reason, exemption)
document = create_attendance_document(employee_name, incident_date, reason, reported_by, history, exemption, counseling)
a_form.save(employee, request, document, counseling)
messages.add_message(request, messages.SUCCESS, 'Attendance Point Successfully Assigned')
return redirect('employee-account', employee_id=employee_id, download_type='attendance')
else:
data = {
'a_form': a_form,
'employee': employee
}
return render(request, 'employees/assign_attendance.html', data)

单个HTTP响应只能触发其中之一。我的方法是重定向到表单视图并在您希望下载文件时传递一个特殊参数,然后使用 Javascript 在浏览器中触发该下载:

window.onload = function(e){ 
window.location.href = '{{your_file_url}}';
}

最新更新