Django custom authentication system


 

 

model.py in app

from django.db Import Models
 from django.contrib.auth.models Import ( 
    BaseUserManager, AbstractBaseUser, PermissionsMixin 
) 

# the Create your Models here Wallpaper. 


class UserProfileManager (BaseUserManager):
     DEF create_user (Self, Email, name, password = None):
         "" " 
        Creating a user 
        " "" 
        IF  not Email:
             The raise ValueError ( ' you must have an e-mail address ' ) 

        the user = self.model ( 
            Email =self.normalize_email(email),
            name=name,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, password):
        """
        创建并保存超级用户
        """
        user = self.create_user(
            email,
            password=password,
            name=name,
        )
        user.is_superuser = True
        user.save(using=self._db)
        return user


class UserProfile(AbstractBaseUser,PermissionsMixin):
    email = models.EmailField(
        verbose_name='邮箱',
        max_length=255,
        unique=True,
    )

    name = models.CharField(max_length=32,verbose_name="用户名")
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)

    objects = UserProfileManager()

    USERNAME_FIELD = 'email'  # 登录的字段
    REQUIRED_FIELDS = ['name']  # 必须要有的字段

    def __str__(self):
        return self.email

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    class Meta:
        permissions = (
            ('make_myself' , ' Custom authority ' ), 
        )

 

 

 

 

settings.py file must be configured:

AUTH_USER_MODEL = 'app01.UserProfile'

 

 

In admin.py app under configuration:

from django import forms

from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from app01.models import UserProfile


class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    password1 = forms.CharField(label='密码', widget=forms.PasswordInput)
    password2 = forms.CharField(label='确认密码', widget=forms.PasswordInput)

    class Meta:
        model = UserProfile
        fields = ('email', '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 forms.ValidationError("密码不匹配")
        return password2

    def save(self, commit=True):
        user = super().save(commit=False)
        # 密码明文根据算法改成密文
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    """A form for updating users. Includes all the fields on
    the user, but replaces the password field with admin's
    password hash display field.
    """
    password = ReadOnlyPasswordHashField()

    class Meta:
        model = UserProfile
        fields = ('email', 'password', 'name', 'is_active',"is_superuser")

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]


class UserProfileAdmin(BaseUserAdmin):
    # The forms to add and change user instances
    form = UserChangeForm
    add_form = UserCreationForm

    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'name', 'is_staff', 'is_active','is_superuser')
    list_filter = ('is_superuser',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('用户信息', {'fields': ('name',)}),
        ('系统权限', {'fields': ('is_superuser','is_staff', 'is_active','user_permissions','groups')}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'name', 'password1', 'password2')}
        ),
    )
    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ('user_permissions','groups')

 

 

 

 

Finally pycharm command line to generate record, and synchronized to the database

 

 Enter the command: python3 manage.py makemigrations

again enter: python3 manage.py migrate

Note: I have here is python3 enter python3 interface, you may be the python. According to their own circumstances!

 

 The final step: Creating a superuser

 

Guess you like

Origin www.cnblogs.com/yunwangjun-python-520/p/11070566.html