【问题标题】:Adding validation to Django User form向 Django 用户表单添加验证
【发布时间】:2016-09-05 12:42:06
【问题描述】:

我想在 Django/Mezzanine 中自定义用户注册表单以只允许某些电子邮件地址,所以我尝试如下进行猴子补丁:

# Monkey-patch Mezzanine's user email address check to allow only
# email addresses at @example.com.
from django.forms import ValidationError
from django.utils.translation import ugettext
from mezzanine.accounts.forms import ProfileForm
from copy import deepcopy
original_clean_email = deepcopy(ProfileForm.clean_email)
def clean_email(self):
    email = self.cleaned_data.get("email")
    if not email.endswith('@example.com'):
        raise ValidationError(
            ugettext("Please enter a valid example.com email address"))
    return original_clean_email(self)
ProfileForm.clean_email = clean_email

此代码添加在我的models.py 之一的顶部。

但是,当我运行服务器时,我会感到害怕

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

如果我添加

import django
django.setup()

然后python manage.py runserver 一直挂到我^C

我应该怎么做才能添加这个功能?

【问题讨论】:

  • 出于兴趣,您为什么认为添加django.setup() 是一种可能的解决方法?它适用于当您在独立脚本中使用 Django 时,您不应该在 models.py 中使用它。
  • 我现在知道了!我在独立脚本中使用它来设置我需要的模型,但没有意识到它在实际的 Django 项目中不起作用。

标签: django python-3.x monkeypatching mezzanine


【解决方案1】:

为您的一个应用程序创建一个文件myapp/apps.py(我在这里使用myapp),并定义一个应用程序配置类,在ready() 方法中执行monkeypatching。

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = 'myapp'

    def ready(self):
        # do the imports and define clean_email here
        ProfileForm.clean_email = clean_email

然后在您的INSTALLED_APPS 设置中使用'myapp.apps.MyAppConfig' 而不是'myapp'

INSTALLED_APPS = [
    ...
    'myapp.apps.MyAppConfig',
    ...
]

您可能需要将 Mezzanine 放在应用配置之上才能使其正常工作。

【讨论】:

  • 谢谢,阿拉斯代尔。我发现我需要将name = 'myapp' 添加到MyAppConfig 类定义中。您能否在答案中提供相关 Django 文档或教程的链接?似乎不容易找到。
  • 我不确定链接到的最佳位置。您可能会发现 django apps 的文档很有帮助。特别是,ready 方法是注册信号的合适位置,在您的情况下,请执行所需的猴子补丁。
  • 我没有意识到name 是必需的,我已经更新了答案。
猜你喜欢
  • 2011-10-07
  • 1970-01-01
  • 2013-09-18
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
相关资源
最近更新 更多