Django Forms clean () method - need a client IP address

I am redefining the clean () method in a Django form. I want to have access to the client's IP address (assuming this is a related form). If I had a reference to the request object, I could easily get it from META ("REMOTE_ADDR"). However, I do not have a link to the request.

Any ideas on how to do this?

+3
source share
1 answer

So give yourself a link 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 opinion:

myform = MyModelForm(request.POST, request=request)
+13
source

Source: https://habr.com/ru/post/1717581/


All Articles