问题描述
我尝试解决的用例是要求用户在被允许进入表单流程的下一阶段之前下载文件.
The use case I am try to address is a requirement for a user to have downloaded a file before being permitted to proceed to the next stage in a form process.
为了实现这一点,我有一个 Django 表单来捕获用户的一般信息,这些信息发布到 Django 视图A".该表单使用一个模板显示,该模板还包括一个带有简单嵌入式按钮的 iFrame,该按钮链接到 Django 视图B"的 URL.
In order to achieve this, I have a Django Form to capture the user's general information which POSTS to Django view 'A'. The Form is displayed using a template which also includes an iFrame with a simple embedded button which links to the URL of Django view 'B'.
View 'B' 只是设置一个会话变量来指示下载已经发生,并返回文件的 URL 进行下载,从而触发下载.
View 'B' simply sets a session variable to indicate that the download has occurred, and returns the URL of the file for download, thereby triggering the download.
作为表单'A'(主表单)验证的一部分,我需要检查是否设置了指示文件下载的会话变量.
As part of the validation of Form 'A' (the main Form), I need to check whether the session variable indicating file download is set.
我的问题是,这是否最好使用A"表验证过程来完成,如果是,如何最好地实现?
My question is, is this best done using Form 'A' validation process, and if so, how is this best achieved?
如果这不是一个好方法,应该在哪里验证此事件?
If this is not a good approach, where should validation of this event take place?
推荐答案
您可以覆盖表单的 __init__
方法,以便它接受 request
作为参数.
You could override the __init__
method for your form so that it takes request
as an argument.
class MyForm(forms.Form):
def __init__(self, request, *args, **kwargs)
self.request = request
super(MyForm, self).__init__(*args, **kwargs)
def clean(self):
if not self.request.session.get('file_downloaded', False):
raise ValidationError('File not downloaded!')
def my_view(request):
form = MyForm(request, data=request.POST)
这将保留表单中的所有验证逻辑.
This keeps all the validation logic in the form.
这篇关于Django 表单验证,包括会话数据的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!