我有一个来自UserCreationForm的注册表单,我已经覆盖了以下内容:
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
import re
from django.core.exceptions import ObjectDoesNotExist
class UserCreationForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'username',)
error_messages = {
'duplicate_username': _("A user with that email already exists."),
'password_mismatch': _("The two password fields didn't match."),
}
username = forms.EmailField(label='Email', max_length=250, unique=True)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = user.username
user.save()
return user
但我收到了一个错误:
NameError at /admin/
name '_' is not defined
所以,我必须导入
from django.utils.translation import gettext as _
这解决了这个问题。但现在,在那之后已经修复(我猜......这是第一个问题的解决方案),我收到了另一个错误:
TypeError at /admin/
__init__() got an unexpected keyword argument 'unique'
如果我从EmailField
删除'unique',一切正常。那么,我是否从表单中删除了unique=true
?它是否总是对每个用户名(这里是它的电子邮件)是唯一的,即使我删除它?还有一件事,是from django.utils.translation import gettext as _
错误名称'_' is not defined
的合适解决方案???我是django的新手。任何帮助将不胜感激!谢谢。
答案 0 :(得分:1)
unique
不是forms.EmailField
的参数。你猜它会与模型领域混淆。
您想使用电子邮件字段作为用户名吗?如果是这样的话,试试这个:
class UserCreationForm(UserCreationForm):
username = forms.EmailField(widget=forms.TextInput(attrs={'maxlength':75}),
label=_("Email"))
至于您对" name' _'的查询没有定义" :
from django.utils.translation import ugettext_lazy as _
这是来自django.contrib.auth.forms代码。