django 自定义用户身份验证
实现自定义用户创建admin管理员
配置 settings.py:
# admin管理默认 AUTH_USER_MODEL = 'web.Account'
数据库 models.py:
class MyUserManager(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): """ 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 Account(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) name = models.CharField(max_length=32) role = models.ForeignKey("Role", blank=True, null=True) customer = models.OneToOneField("Customer", blank=True, null=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): # The user is identified by their email address return self.name def get_short_name(self): # The user is identified by their email address return self.email def __str__(self): return 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
urls.py
from django.conf.urls import url from web import views # 登录登出 urlpatterns = [ url(r'^$', views.index), url(r'^login/$', views.account_login), url(r'^logout/$', views.account_logout, name='logout'), ]
用户登录验证
views.py
from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from web import models # django 内置验证、登录、登出 from django.contrib.auth import authenticate, login, logout @login_required(login_url='/crm/login/') def index(request): return render(request, 'index.html') def account_logout(request): logout(request) return redirect('/crm/') def account_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') # django自带验证用户名密码 user = authenticate(username=username, password=password) if user: login(request, user) return redirect(request.GET.get('next') or '/crm/') return render(request, 'login.html')
admin中创建用户
admin.py
from django.contrib import admin from web import models # Register your models here. 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 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 = models.Account fields = ('email', 'name', 'is_active', 'is_admin') 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(UserCreationForm, self).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 = models.Account 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 AccountAdmin(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 = ( ('test', {'fields': ('email', 'password')}), ('Personal info', {'fields': ('name', 'customer')}), ('Permissions', {'fields': ('is_admin', 'role')}), ) # 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 = () # Now register the new UserAdmin... admin.site.register(models.Account, AccountAdmin)
详细参考官方文档:https://docs.djangoproject.com/en/1.11/topics/auth/