django login logout request使用

情景一

User表继承django默认的AbstractUser

class User(AbstractUser):
    state = models.CharField(max_length=1, default=1)

    def __str__(self):
        return self.state

需要在settings中添加配置项目:

AUTH_USER_MODEL = 'li.User'
# AUTH_USER_MODEL = '某个app.User'

登录\退出 逻辑代码

from django.contrib import auth
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.views import View
from li.models import *
from django.http import JsonResponse


class Login(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        params = request.POST
        name = params.get('name')
        pwd = params.get('password')


        user = auth.authenticate(username=name, password=pwd)
        if user:
            login(request, user)
            return redirect('/home/')
		return JsonResponse({"code":0, "msg":"登录失败"}, json_dumps_params={'ensure_ascii': False}, safe=False)


class Logout(View):
    def post(self, request):
        if request.user:
            logout(request)
        return JsonResponse({"code": 0, "msg": "退出成功"}, json_dumps_params={'ensure_ascii': False}, safe=False)

情景二

User表不继承django默认的AbstractUser

其中的last_login字段是必须的,在使用login()时会使用

class MyUser(models.Model):
    username = models.CharField(max_length=12)
    password = models.CharField(max_length=12)
    last_login = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return self.username

这个时候如果想使用request.user,必须在settings中添加配置项目:

AUTHENTICATION_BACKENDS = (
    'li.myAuth.auth.ZhUserBackend',
)

此为函数:

class ZhUserBackend(object):
    """
    自定义用户验证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        from li.models import MyUser
        try:
            user = MyUser.objects.get(username=username)
            if user:
                return user

        except Exception as e:
            return None

    def get_user(self, user_id):
        from li.models import MyUser
        return MyUser.objects.get(id=user_id)

这样才能在其他路由中继续使用request.user

登录\退出 逻辑代码

from django.contrib import auth
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.views import View
from li.models import *


class Login(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        params = request.POST
        name = params.get('name')
        pwd = params.get('password')
        user = auth.authenticate(username=name, password=pwd)
        if user:
            login(request, user)
            return redirect('/home/')
        return JsonResponse({"code":0, "msg":"登录失败"}, json_dumps_params={'ensure_ascii': False}, safe=False)


class Logout(View):
    def post(self, request):
        if request.user:
            logout(request)
        return JsonResponse({"code": 0, "msg": "退出成功"}, json_dumps_params={'ensure_ascii': False}, safe=False)

你可能感兴趣的:(Django)