我有以下代码:
型号:
class MyUser(AbstractUser):
profile = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT)
My profile model contains only some personal fields like full_name, gender, birthdate, etc.
管理员:
class MyUserInline(admin.StackedInline):
model = MyUser
fieldsets = .....
filter_horizontal = ....
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = MyUser
def clean_password(self):
return ""
class ProfileAdmin(admin.ModelAdmin):
inlines = (MyUserInline,)
change_user_password_template = None
form = MyUserChangeForm
change_password_form = AdminPasswordChangeForm
def save_model(self, request, obj, form, change):
if not Profile.objects.filter(myuser__username=obj.myuser.email).exclude(pk=obj.id).exists():
obj.myuser.username = obj.myuser.email
obj.save()
else:
# *MY PROBLEM IS HERE!*
我要做的是从管理员更改用户页面删除用户名字段,并将其电子邮件也设置为用户名。在AbstractUser
中,电子邮件不是唯一的,但用户名是唯一的。问题是更改用户电子邮件时,如果电子邮件重复,则会引发异常,但我想显示错误以说该电子邮件已重复。这样做是改变我的MyUser
模型并将电子邮件添加为唯一字段的唯一方法,还是我可以做其他事情?
tnx