gpt4 book ai didi

python - 使 User.email 与 Django Admin 保持唯一

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:06 24 4
gpt4 key购买 nike

我正在使用 Django 1.3/Python 2.7。

我的应用程序使用 django.contrib.auth 进行用户管理。对于主要用户注册,我有一个表格来检查“电子邮件”是否已经注册。因此它确保所有电子邮件字段都是唯一的。

但碰巧有些管理员使用 django 管理界面添加用户,并最终添加了具有相同电子邮件的重复帐户。

为此,我创建了一个 NewUserCreationForm,我在其中复制了 django.contrib.auth.UserCreationForm 并向其添加了一个“电子邮件”字段。

class NewUserCreationForm(forms.ModelForm):
"""
A form that creates a user, with no privileges, from the given username and password.
"""
username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^[\w.@+-]+$',
help_text = _("Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only."),
error_messages = {'invalid': _("This value may contain only letters, numbers and @/./+/-/_ characters.")})
password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput,
help_text = _("Enter the same password as above, for verification."))
email = forms.EmailField(label=_("Email"), max_length=75)

class Meta:
model = User
fields = ("username", "email")

def clean_username(self):
username = self.cleaned_data["username"]
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError(_("A user with that username already exists."))

def clean_password2(self):
password1 = self.cleaned_data.get("password1", "")
password2 = self.cleaned_data["password2"]
if password1 != password2:
raise forms.ValidationError(_("The two password fields didn't match."))
return password2

def save(self, commit=True):
user = super(NewUserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.email
if commit:
user.save()
return user


class CustomUserAdmin(UserAdmin):
add_form = NewUserCreationForm


admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

但是这段代码不起作用。我可以看到表单呈现,但没有电子邮件字段,只有用户名、密码 1 和密码 2 字段。

我在这里缺少什么?

最佳答案

您缺少... UserAdmin.add_fieldsets,例如:

class CustomUserAdmin(UserAdmin):
add_form = NewUserCreationForm
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'email')}
),
)

关于python - 使 User.email 与 Django Admin 保持唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9633043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com