Django表单验证,包括会话数据的使用 [英] Django Form validation including the use of session data

查看:29
本文介绍了Django表单验证,包括会话数据的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要解决的用例是用户必须先下载文件,然后才能进入表单处理的下一阶段.

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表单来捕获用户的一般信息,这些信息是POSTS到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'.

视图'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 作为参数./p>

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表单验证,包括会话数据的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆