如何将用户对象或请求传递给表单进行验证?
例如,我希望能够做到这样的事情 -
class Form(forms.Form):
...
def clean(self)
user = request.user # how to get request.user here?
user = User # how to pass the actual User object?
谢谢。
答案 0 :(得分:32)
将其传递给构造函数并将其存储为实例变量:
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super(MyForm, self).__init__(*args, **kwargs)
def clean(self):
print self.request.user
...
在您看来:
form = MyForm(..., request=request)
如果使用基于类的视图(在此示例中为CreateView):
class MyCreateView(CreateView):
...
def get_form_kwargs(self):
kwargs = super(MyCreateView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs