自定義Django中自帶的用戶與用戶認證

自定義用戶:

寫一個繼承自AbstractUser的類,而後追加本身須要的字段,好比新增電話號碼和年齡字段html

在settings.py加入AUTH_USER_MODEL = 'app的名字.用戶類'django

models:

class MyUser(AbstractUser):
    phone = models.CharField(max_length=13)
    age = models.IntegerField(null=True)

而後進行遷移,若以前進行過遷移會報錯,須要刪除遷移記錄與已建立的表,從新進行遷移。app

在app的目錄下新鍵一個文件 auth.py,寫一個繼承自ModeBackend的類,複寫authenticate函數(根據姓名或者電話號碼查找對象,而後校驗密碼)。函數

在settings.py裏設置:AUTHENTICATION_BACKENDS=("app的名字.文件名字.類",)url

auth.py:

from django.contrib.auth.backends import ModelBackend

from .models import MyUser

class MyBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = MyUser.objects.get(username=username)
        except Exception:
            try:
                user = MyUser.objects.get(phone=username)
            except Exception:
                return None

        # 密碼校驗
        if user.check_password(password):
            return user
        else:
            return None

views函數(首頁,登陸,註冊,登出):

from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse


def index(req):
    user = req.user
    uname = user.username if user.username else '遊客'
    return render(req,'new_index.html',{'user_name':uname})


def mylogin(req):
    if req.method == 'GET':
        return render(req,'new_login.html')
    else:
        name = req.POST.get('name')
        pwd = req.POST.get('pwd')
        if len(name) == 0 or len(pwd) == 0:
            return HttpResponse('用戶名密碼不能爲空')
        # 校驗用戶
        user = authenticate(req,username = name, password = pwd)
        if user is None:
            return HttpResponse('帳號或密碼錯誤')
        else:
            login(req,user)
            return redirect('/app2/index')


def register(req):
    if req.method == 'GET':
        return render(req,'register.html')
    else:
        name = req.POST.get('name')
        pwd = req.POST.get('pwd')
        confirm_pwd = req.POST.get('confirm_pwd')
        if pwd and len(pwd) >= 4 and pwd == confirm_pwd:
            if not User.objects.filter(username=name).exists():
                user = User.objects.create_user(username=name,password=pwd)
                return redirect(reverse('app2:mylogin'))
        else:
            return HttpResponse('帳號或者密碼有誤')


def mylogout(req):
    logout(req)
    return redirect('/app2/index')
相關文章
相關標籤/搜索