码迷,mamicode.com
首页 > 编程语言 > 详细

python/django models中自定义用户认证及django admin自定义

时间:2020-05-26 15:19:19      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:com   comm   instance   dHash   bec   upd   require   length   uniq   

python django models中自定义用户认证

#(一)
#简单的用户验证
# from django.contrib.auth.models import User
# class UserProfile(models.Model):s
#     ‘‘‘堡垒机账户‘‘‘
#     user = models.OneToOneField(User,on_delete=models.CASCADE)  #django官方推荐的简单方法,缺点是找user时要a.user.username
#     name =models.CharField(max_length=32)
#
#     def __str__(self):
#         return self.name
#(二)
#常用的版本,自定义
#导入自定义用户认证表 UseProfile

from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)
#自定义用户认证
class UserProfileManager(BaseUserManager):
    def create_user(self, email, name, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError(‘Users must have an email address‘)

        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=None):
        """
        Creates and saves a superuser with the given email, date of
        birth and password.
        """
        user = self.create_user(
            email,
            password=password,
            name=name,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user

class UserProfile(AbstractBaseUser):
    email = models.EmailField(
        verbose_name=‘email address‘,
        max_length=255,
        unique=True,
    )
    # date_of_birth = models.DateField()
    name = models.CharField(max_length=32)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    bind_hosts = models.ManyToManyField(‘BindHost‘,blank=True)
    host_groups = models.ManyToManyField(‘HostGroups‘,blank=True)

    objects = UserProfileManager()

    USERNAME_FIELD = ‘email‘ #登录的用户名
    REQUIRED_FIELDS = [‘name‘] #必填字段

    def __str__(self):
        return ‘email:‘+self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        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
 在settings.py中加上
     #用自定义的用户认证 (app名+表)
     AUTH_USER_MODEL = ‘web.UserProfile‘

django amdin自定义

#新建一个py文件,customer_user_admin.py
#1)
# -*- coding: utf-8 -*-
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField

from web.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=‘Password‘, widget=forms.PasswordInput)
    password2 = forms.CharField(label=‘Password confirmation‘, widget=forms.PasswordInput)

    class Meta:
        model = UserProfile
        fields = (‘email‘, ‘name‘,‘is_admin‘,‘bind_hosts‘,‘host_groups‘)

    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("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

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_admin‘)

    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 UserAdmin(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_admin‘)
    list_filter = (‘is_admin‘,)
    fieldsets = (
        (None, {‘fields‘: (‘email‘, ‘password‘)}),
        (‘Personal info‘, {‘fields‘: (‘name‘,)}),
        (‘Permissions‘, {‘fields‘: (‘is_admin‘,‘bind_hosts‘,‘host_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‘,‘is_admin‘,‘bind_hosts‘,‘host_groups‘),
        }),
    )
    search_fields = (‘email‘,)
    ordering = (‘email‘,)
    filter_horizontal = (‘bind_hosts‘,‘host_groups‘)

# Now register the new UserAdmin...
admin.site.register(UserProfile, UserAdmin)
# ... and, since we‘re not using Django‘s built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)

#2)
在admin.py中导入py文件,就会自动执行注册(admin.site.register(UserProfile, UserAdmin))
from web import customer_user_admin

python/django models中自定义用户认证及django admin自定义

标签:com   comm   instance   dHash   bec   upd   require   length   uniq   

原文地址:https://www.cnblogs.com/hanfe1/p/12965481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!