Passing a user, request to forms

六月ゝ 毕业季﹏ 提交于 2020-01-19 07:34:09

问题


How would I pass a user object or a request to my form for validation?

For example, I want to be able to do something like this --

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?

Thank you.


回答1:


Just pass it into the constructor and store it as an instance variable:

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
        ...

In your view:

form = MyForm(..., request=request)

And if using a class-based view (a CreateView in this example):

class MyCreateView(CreateView):

    ... 

    def get_form_kwargs(self):
        kwargs = super(MyCreateView, self).get_form_kwargs()
        kwargs.update({'request': self.request})
        return kwargs


来源:https://stackoverflow.com/questions/6325681/passing-a-user-request-to-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!