Django Forms clean()方法 - 需要客户端的IP地址 [英] Django Forms clean() method - need IP address of client

查看:438
本文介绍了Django Forms clean()方法 - 需要客户端的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django表单上覆盖了clean()方法。我想访问客户端的IP地址(假设这是一个绑定的表单)。如果我有一个对请求对象的引用,我可以从META(REMOTE_ADDR)轻松获取它。但是,我没有参考请求。



任何有关如何做到这一点的想法?

解决方案

给你自己一个参考。

  class MyModelForm(forms.ModelForm):
def __init __(self,* args ,** kwargs)
self.request = kwargs.pop('request',None)
super(MyModelForm,self).__ init __(* args,** kwargs)


def clean(self):
ip_address = self.request ['META'] ['REMOTE_ADDR']

,在您的看法中:

  myform = MyModelForm(request.POST,request = request )


I am overriding the clean() method on a Django form. I want to have access to the IP address of the client (assuming this is a bound form). If I had a reference to the request object, I could get it easily from META("REMOTE_ADDR"). However, I do not have a reference to the request.

Any ideas on how this could be done?

解决方案

So give yourself a reference to it.

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyModelForm, self).__init__(*args, **kwargs)


    def clean(self):
        ip_address = self.request['META']['REMOTE_ADDR']

and in your view:

myform = MyModelForm(request.POST, request=request)

这篇关于Django Forms clean()方法 - 需要客户端的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆