Question

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?

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top