Reputation:
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()
Upvotes: 5
Views: 3966
Reputation: 3290
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/
Upvotes: 3
Reputation: 14311
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
Upvotes: 3