简体   繁体   中英

Django - How to add user's IP address when form is POSTed

I know that if I'm inside of a request function, I can get the user's IP address using ipware.ip's get_ip(request) or other methods, but I'm using a view of (ListView, FormView) so I'm not sure how I would add the IP to the form like I normally would by using:

instance = form.save(commit=False)
instance.ip = get_ip(request)
instance.save()

It's pretty straightforward, use request.META['REMOTE_ADDR'] .

instance = form.save(commit=False)
instance.ip = self.request.META['REMOTE_ADDR']
instance.save()

request.META (and request in general) has all kinds of useful information. More information in the docs: https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.META

If you cannot access self.request , here's one way to solve it:

class SignUpForm(forms.ModelForm):
    fullname = forms.CharField(label="Full name", widget=forms.TextInput(attrs={'placeholder': 'Full name', 'class': 'form-control'}))
    class Meta:
        model = SignUps
        fields = ['eventname','fullname','ip']

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None) # Now you use self.request to access request object.
        super(SignUpForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        instance =  super(SignUpForm, self).save(commit=False)
        instance.fullname = fullname
        instance.ip = get_ip(self.request)
        if commit:
            instance.save()
        return instance

http://brunobastos.net/how-to-access-the-httprequest-object-in-django-forms/

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