Tuesday, July 31, 2012

Get the View's request object as self.request in your Form Subclass!!!


http://stackoverflow.com/questions/1057252/how-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clean-met

Again, like in many other Django things, you must have access to pass in arguments to the constructor of a Django object, AND THEN, have access to override the __init__ method of that Django object, so that it can take in and process your constructor argument as part of its self.





Scenario,
you have a Form/ModelForm subclass, which needs to do validation on some View request variable.

you want to access in your Form subclass, it as self.request


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



A much better way is to override the form's __init__ method to take an extra keyword argument,request. This stores the request in the form, where it's required, and from where you can access it in your clean method.
class MyForm(forms.Form):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyForm, self).__init__(*args, **kwargs)


    def clean(self):
        ... access the request object via self.request ...
and in your view:
myform = MyForm(request.POST, request=request)








No comments:

Post a Comment