Django - 如何在表单发布时添加用户的IP地址

时间:2016-12-05 23:06:43

标签: python django forms listview ip

我知道如果我在请求函数中,我可以使用ipware.ip的get_ip(request)或其他方法获取用户的IP地址,但我正在使用(ListView, FormView)的视图我不确定如何将IP添加到表单中,就像我通常使用的那样:

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

2 个答案:

答案 0 :(得分:4)

如果您无法访问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/

答案 1 :(得分:3)

非常简单,请使用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