T_T*_*ure 1 python authentication django
我在 Django 项目中定义了一个自定义用户模型,它将“电子邮件”定义为唯一标识符。我按照 Django 文档创建了一个自定义用户创建表单,并将其注册到我的 admin.py 中。当我启动 Web 服务器时,控制台中没有显示任何错误。
我的问题是,add_form管理页面上不显示“电子邮件”字段,而只显示“用户名”、“密码1”和“密码2”
我阅读了一些操作方法和教程,并检查了 Django 文档来解决这个问题,但我担心我遗漏了一些东西。
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users.apps.UsersConfig'
]
AUTH_USER_MODEL = 'users.NewUser'
Run Code Online (Sandbox Code Playgroud)
# Custom User Account Model
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
class CustomAccountManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
"""
def create_user(self, email, username, first_name, last_name, password=None, **other_fields):
if not last_name:
raise ValueError(_('Users must have a last name'))
elif not first_name:
raise ValueError(_('Users must have a first name'))
elif not username:
raise ValueError(_('Users must have a username'))
elif not email:
raise ValueError(_('Users must provide an email address'))
user = self.model(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
**other_fields
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, first_name, last_name, password=None, **other_fields):
"""
Create and save a SuperUser with the given email and password.
"""
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_admin', True)
user = self.create_user(
email=self.normalize_email(email),
username=username,
first_name=first_name,
last_name=last_name,
password=password,
**other_fields
)
if other_fields.get('is_staff') is not True:
raise ValueError('Superuser must be assigned to is_staff=True.')
if other_fields.get('is_superuser') is not True:
raise ValueError('Superuser must be assigned to is_superuser=True.')
user.save(using=self._db)
return user
class NewUser(AbstractBaseUser, PermissionsMixin):
# basic information
email = models.EmailField(_('email address'), unique=True)
username = models.CharField(max_length=150, unique=True)
first_name = models.CharField(max_length=150, blank=True)
last_name = models.CharField(max_length=150, blank=True)
# Registration Date
date_joined = models.DateTimeField(default=timezone.now) ## todo: unterschied zu 'auto_now_add=True'
# Permissions
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] # Note: USERNAME_FIELD not to be included in this list!
def __str__(self):
return self.email
# For checking permissions. to keep it simple all admin have ALL permissons
def has_perm(self, perm, obj=None):
return self.is_admin
# Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY)
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
Run Code Online (Sandbox Code Playgroud)
from django import forms
from django.contrib import admin
from django.core.exceptions import ValidationError
# Import custom user model
from django.contrib.auth import get_user_model
custom_user_model = get_user_model()
class CustomUserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
username = forms.CharField(label='Username', min_length=4, max_length=150)
email = forms.EmailField(label='E-Mail')
first_name = forms.CharField(label='First Name')
last_name = forms.CharField(label='Last Name')
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = custom_user_model
fields = ('username', 'first_name', 'last_name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
Run Code Online (Sandbox Code Playgroud)
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin # Helper Class for creating user admin pages
from .forms import CustomUserCreationForm #, CustomUserChangeForm
from .models import NewUser, UserProfile
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
model = NewUser
list_display = ('email', 'username', 'date_joined', 'last_login', 'is_admin', 'is_staff')
search_fields = ('email', 'username',)
readonly_fields = ('date_joined', 'last_login',)
filter_horizontal = ()
list_filter = ()
fieldsets = ()
admin.site.register(custom_user_model, CustomUserAdmin)
Run Code Online (Sandbox Code Playgroud)
小智 6
将此代码添加到 CustomeUserAdmin:
类自定义用户管理(用户管理):
。
。
。
add_fieldsets = UserAdmin.add_fieldsets + (
(无,{'fields': ('custom_field',)}),
)
看起来 django 管理页面上的表单是基于 add_fieldsets 创建的。我也不知道 add_form 实际上是做什么的。
有关更多信息,请阅读 django 文档: 关于 admin 的 django 文档,django admin 中 Custome 用户的完整示例
如果您使用的是自定义 ModelAdmin,它是 django.contrib.auth.admin.UserAdmin 的子类,那么您需要将自定义字段添加到 fieldsets(用于编辑用户时使用的字段)和 add_fieldsets(用于要编辑的字段)创建用户时使用)。
| 归档时间: |
|
| 查看次数: |
3823 次 |
| 最近记录: |