如何在表单的 clean() 方法中访问请求对象或任何其他变量? [英] How do I access the request object or any other variable in a form's clean() method?

查看:20
本文介绍了如何在表单的 clean() 方法中访问请求对象或任何其他变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 request.user 以获取表单的清理方法,但是如何访问请求对象?可以修改clean方法允许变量输入吗?

I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?

推荐答案

Ber 的答案 - 将其存储在 threadlocals - 是一个非常糟糕的主意.绝对没有理由这样做.

The answer by Ber - storing it in threadlocals - is a very bad idea. There's absolutely no reason to do it this way.

更好的方法是覆盖表单的 __init__ 方法以采用额外的关键字参数 request.这会将请求存储在表单中,在需要它的地方,以及您可以在干净的方法中从哪里访问它.

A much better way is to override the form's __init__ method to take an extra keyword argument, request. This stores the request in the form, where it's required, and from where you can access it in your clean method.

class MyForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyForm, self).__init__(*args, **kwargs)


    def clean(self):
        ... access the request object via self.request ...

在您看来:

myform = MyForm(request.POST, request=request)

这篇关于如何在表单的 clean() 方法中访问请求对象或任何其他变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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