如何在表单的clean()方法中访问请求对象或任何其他变量? [英] How do I access the request object or any other variable in a form's clean() method?
本文介绍了如何在表单的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 __
方法覆盖采取额外的关键字参数请求
。它将请求存储在需要的表单中,您可以通过干净的方法访问该请求。
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屋!
查看全文