如何在AbstractUser模型中修改电子邮件域以便需要电子邮件

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (14)

如何在扩展AbstractUser时将emailfield设置为必需?

我想知道如何覆盖AbstractUser的emailfield模型以根据需要进行设置。目前我的表单列出了电子邮件字段,但没有按要求设置。默认情况下不应该要求所有型号?

从文档中可以看到如何在创建超级用户时将字段设置为必需的示例,但我不确定如何在不使用AbstractBaseUser的情况下从AbstractUser模型完成任务。


model.py

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    display_name = models.CharField(max_length=50, unique=True)
    bio = models.CharField(max_length=500, blank=True, null=True)
    authorization_code = models.CharField(max_length=20)


forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):

    class Meta (UserCreationForm):
        model = CustomUser
        fields = ('username', 'email', 'display_name', 'authorization_code')

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'bio')


admin.py

from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username', 'display_name', 'bio']
    list_display_links = ('username', 'display_name')

    fieldsets = (
        (None, {'fields': ('username', 'display_name', 'email', 'bio', 'password')}),
        ('Permissions', {'fields': ('is_staff', 'is_active')}),
    )

    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'display_name', 'email', 'bio', 'password1', 'password2', 'is_staff', 'is_active')}
         ),
    )



admin.site.register(CustomUser, CustomUserAdmin)

解:


# It was as simple as updating my CustomUser model as shown:

class CustomUser(AbstractUser):
    display_name = models.CharField(max_length=50, unique=True)
    bio = models.CharField(max_length=500, blank=True, null=True)
    authorization_code = models.CharField(max_length=20)
    email = models.EmailField(max_length=50, unique=True)
提问于
用户回答回答于

您可以通过重写做到emailAbstractBaseUser

from django.contrib.auth.models import AbstractBaseUser, UserManager

class User(AbstractBaseUser):
    email = models.EmailField(_('email address'), blank=False)       
    objects = UserManager()

所属标签

可能回答问题的人

  • 嗨喽你好

    7 粉丝480 提问8 回答
  • 人生的旅途

    10 粉丝484 提问7 回答
  • uncle_light

    5 粉丝518 提问7 回答
  • 无聊至极

    4 粉丝504 提问6 回答

扫码关注云+社区

领取腾讯云代金券