[英]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: 我知道如果我在请求函数内,我可以使用ipware.ip的
get_ip(request)
或其他方法获取用户的IP地址,但我使用的是(ListView, FormView)
视图,所以我不是确定如何将IP添加到表单中,就像我通常使用的那样:
instance = form.save(commit=False)
instance.ip = get_ip(request)
instance.save()
It's pretty straightforward, use request.META['REMOTE_ADDR']
. 它非常简单,请使用
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. request.META
(和一般request
)有各种有用的信息。 More information in the docs: https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.META 文档中的更多信息: 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: 如果你无法访问
self.request
,这是解决它的一种方法:
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/ http://brunobastos.net/how-to-access-the-httprequest-object-in-django-forms/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.