【发布时间】: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