在 Django 的 models.py 中,如果我正在验证表单,如何获取用户的 IP?

发布于 2024-10-07 21:28:08 字数 112 浏览 0 评论 0原文

我知道如何在views.py中获取它......

request.META['REMOTE_ADDR']

但是,当我的其中一个表单正在验证时,如何在models.py中获取它?

I know how to get it in views.py....

request.META['REMOTE_ADDR']

However, how do I get it in models.py when one of my forms is being validateD?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

那请放手 2024-10-14 21:28:08

您可以将请求对象传递给正在调用的表单/模型代码:然后,这将提供对 request.META['REMOTE_ADDR'] 的访问。或者,只需将其传递进去即可。

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']. Alternatively, just pass that in.

不交电费瞎发啥光 2024-10-14 21:28:08

一个可能的方法,但我不确定它是否是最好的...

定义你自己的干净方法,

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

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
深巷少女 2024-10-14 21:28:08

如果您在表单级别或模型级别进行验证,则两个实例对 HTTP 请求(存储客户端 IP 信息的位置)一无所知。

我可以想到两个选项:

  • 在视图级别进行验证,您可以将错误插入表单错误列表中。
  • 您可以将用户 IP(可能已加密)放入表单的隐藏字段中。

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).

I can think of two options:

  • Validate at the view level where you can insert errors into the form error list.
  • You can put the user IP (may be encrypted) in a hidden field at your form.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文