[英]Inside Django's models.py, if I am validating a form, how do I get the user's IP?
I know how to get it in views.py.... 我知道如何在views.py中获取它。
request.META['REMOTE_ADDR'] request.META ['REMOTE_ADDR']
However, how do I get it in models.py when one of my forms is being validateD? 但是,当我的表单之一为validateD时,如何在models.py中获取它?
You can pass the request object to the form/model code that is being called: this will then provide access to request.META['REMOTE_ADDR']
. 您可以将请求对象传递给正在调用的表单/模型代码:然后将提供对
request.META['REMOTE_ADDR']
。 Alternatively, just pass that in. 或者,只需将其传入。
If you are validating at form level or at model level, both instances know nothing about the HTTP request (where the client IP info is stored). 如果要在表单级别或模型级别进行验证,则两个实例都不知道HTTP请求(存储客户端IP信息的位置)。
I can think of two options: 我可以想到两种选择:
Ona possible way, but i am not sure if it is the best or not... 一种可能的方法,但是我不确定这是否是最好的方法。
define your own clean method, 定义自己的清洁方法,
class someForm(forms.Form):
afield = CharField()
def clean(self, **kwargs):
cleaned_data = self.cleaned_data
afield = cleaned_data.get('afield')
if 'ip' in kwargs:
ip = kwargs['ip']
# ip check block, you migth use your cleaned data in here
return cleaned_data
some_info = {'afield':123} #you will wish to use post or gt form data instead, but tihs iis for example
form = someForm(some_info)
if form.is_valid():
data = form.clean({'ip':request.META['REMOTE_ADDR']}) # you pass a dict with kwargs, which wwill be used in custom clean method
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.