[英]How to save the form with posted user in the django models database
[英]Django - How to add user's IP address when form is POSTed
我知道如果我在請求函數內,我可以使用ipware.ip的get_ip(request)
或其他方法獲取用戶的IP地址,但我使用的是(ListView, FormView)
視圖,所以我不是確定如何將IP添加到表單中,就像我通常使用的那樣:
instance = form.save(commit=False)
instance.ip = get_ip(request)
instance.save()
它非常簡單,請使用request.META['REMOTE_ADDR']
。
instance = form.save(commit=False)
instance.ip = self.request.META['REMOTE_ADDR']
instance.save()
request.META
(和一般request
)有各種有用的信息。 文檔中的更多信息: https : //docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.META
如果你無法訪問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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.