Alex Rivera | Logout

How do I access the request object or any other variable in a form's clean() method?

Asked 2009-06-29T08:49:45.623
112

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?

Edit
Report

2 Answers

37

UPDATED 10/25/2011: I'm now using this with a dynamically created class instead of method, as Django 1.3 displays some weirdness otherwise.

class MyModelAdmin(admin.ModelAdmin):
    form = MyCustomForm
    def get_form(self, request, obj=None, **kwargs):
        ModelForm = super(MyModelAdmin, self).get_form(request, obj, **kwargs)
        class ModelFormWithRequest(ModelForm):
            def __new__(cls, *args, **kwargs):
                kwargs['request'] = request
                return ModelForm(*args, **kwargs)
        return ModelFormWithRequest

Then override MyCustomForm.__init__ as follows:

class MyCustomForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyCustomForm, self).__init__(*args, **kwargs)

You can then access the request object from any method of ModelForm with self.request.

answered 2011-05-19T17:39:58.730
3

I have another answer to this question as per your requirement you want to access the user into the clean method of the form. You can Try this. View.py

person=User.objects.get(id=person_id)
form=MyForm(request.POST,instance=person)

forms.py

def __init__(self,*arg,**kwargs):
    self.instance=kwargs.get('instance',None)
    if kwargs['instance'] is not None:
        del kwargs['instance']
    super(Myform, self).__init__(*args, **kwargs)

Now you can access the self.instance in any clean method in form.py

answered 2012-04-02T09:46:31.597

Your Answer