通过用户,请求形成表格

问题描述

| 如何将用户对象或请求传递给表单进行验证? 例如,我希望能够做这样的事情-
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?
谢谢。     

解决方法

        只需将其传递给构造函数并将其存储为实例变量即可:
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