经过一番挖掘后,我发现了这个
https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#custom-users-and-the-built-in-auth-forms
罪魁祸首是clean_username
inside UserCreationForm
inside的一个函数django.contrib.auth.forms.py
。已经创建了一些票证,但显然维护人员并不认为这是一个缺陷:
https://code.djangoproject.com/ticket/20188
https://code.djangoproject.com/ticket/20086
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
此User
文件中的 直接引用内置用户模型。
为了解决这个问题,我创建了我的自定义表单
from models import User #you can use get_user_model
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth import forms
class MyUserCreationForm(UserCreationForm):
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
User._default_manager.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(self.error_messages['duplicate_username'])
class Meta(UserCreationForm.Meta):
model = User
class MyUserAdmin(UserAdmin):
add_form = MyUserCreationForm
admin.site.register(User,MyUserAdmin)
或者您可以尝试猴子修补原始文件UserCreationForm
以替换User
变量。