我想在Django/夹层中自定义用户注册表单,使其只允许某些电子邮件地址,因此我尝试按以下方式进行猴子修补:
# 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。
我应该做些什么来添加这个功能?
发布于 2016-05-10 13:48:52
为您的一个应用程序创建一个文件myapp/apps.py (我在这里使用了myapp ),并定义了一个app配置类,用于在ready()方法中进行猴子切换。
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'而不是'myapp'。
INSTALLED_APPS = [
...
'myapp.apps.MyAppConfig',
...
]您可能需要将夹层置于应用程序配置之上,这样它才能工作。
https://stackoverflow.com/questions/37140180
复制相似问题