get request data in Django form

前端 未结 4 1428
有刺的猬
有刺的猬 2020-11-28 23:11

Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it\'s unique, but if it\'s the current users email address then

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 23:22

    Here's the way to get the user in your form when using generic views:

    In the view, pass the request.user to the form using get_form_kwargs:

    class SampleView(View):
        def get_form_kwargs(self):
            kwargs = super(SampleView, self).get_form_kwargs()
            kwargs['user'] = self.request.user
            return kwargs
    

    In the form you will receive the user with the __init__ function:

    class SampleForm(Form):
        def __init__(self, user, *args, **kwargs):
            super(SampleForm, self).__init__(*args, **kwargs)
            self.user = user
    

提交回复
热议问题