向Django用户表单添加验证

时间:2016-05-10 13:35:29

标签: django python-3.x monkeypatching mezzanine

我想在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之一的顶部。

然而,当我运行runserver时,我得到了可怕的

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

如果我添加

import django
django.setup()

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

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

1 个答案:

答案 0 :(得分:2)

为您的某个应用创建文件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

然后在'myapp.apps.MyAppConfig'设置中使用'myapp'代替INSTALLED_APPS

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

您可能需要将Mezzanine放在app配置上方才能正常工作。

相关问题