简体   繁体   中英

Inside Django's models.py, if I am validating a form, how do I get the user's IP?

I know how to get it in views.py....

request.META['REMOTE_ADDR']

However, how do I get it in models.py when one of my forms is being validateD?

You can pass the request object to the form/model code that is being called: this will then provide access to request.META['REMOTE_ADDR'] . Alternatively, just pass that in.

If you are validating at form level or at model level, both instances know nothing about the HTTP request (where the client IP info is stored).

I can think of two options:

  • Validate at the view level where you can insert errors into the form error list.
  • You can put the user IP (may be encrypted) in a hidden field at your form.

Ona possible way, but i am not sure if it is the best or not...

define your own clean method,

class someForm(forms.Form):
    afield = CharField()

    def clean(self, **kwargs):
        cleaned_data = self.cleaned_data
        afield = cleaned_data.get('afield')
        if 'ip' in kwargs:
            ip = kwargs['ip']
            # ip check block, you migth use your cleaned data in here
        return cleaned_data


some_info = {'afield':123} #you will wish to use post or gt form data instead, but tihs iis for example
form = someForm(some_info) 
if form.is_valid():
    data = form.clean({'ip':request.META['REMOTE_ADDR']}) # you pass a dict with kwargs, which wwill be used in custom clean method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM