views:

463

answers:

1

I am overriding the clean() method on a Django form. I want to have access to the IP address of the client (assuming this is a bound form). If I had a reference to the request object, I could get it easily from META("REMOTE_ADDR"). However, I do not have a reference to the request.

Any ideas on how this could be done?

+9  A: 

So give yourself a reference to it.

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


    def clean(self):
        ip_address = self.request['META']['REMOTE_ADDR']

and in your view:

myform = MyModelForm(request.POST, request=request)
Daniel Roseman
Why pop() it? Is that for cleanliness (like get rid of stuff you're not using)? Or, is it more efficient than get().
orokusaki
It's generally good practice. It's possible for example that the superclass method doesn't actually accept *args and **kwargs - it might only have named arguments in its definition. If so, passing the unexpected `request` argument will cause an exception.
Daniel Roseman