django 自带认证系统(login,logout,authenticate,login_required)

from django.contrib.auth import login,authenticate,logout
from django.contrib.auth.decorators import login_required

setting.py
AUTH_USER_MODEL = 'mytest.User'         #app名字.表名字
LOGIN_URL="/mytest/login/"              #如果没有登录,将会返回的url,用于装饰器 @login_required()

model.py(重构User model)
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.
class User(AbstractUser):
nickname = models.CharField(max_length=50, blank=True)

class Meta(AbstractUser.Meta):
verbose_name = "用户信息"
verbose_name_plural = verbose_name

def __str__(self):
return self.username

view.py
def acc_login(req):
if req.method == "GET":
return render(req,"acc_login.html")
else:
email=req.POST.get("acc")
pwd=req.POST.get("pwd")
print("user:%s-%s" % (email,pwd))
user=authenticate(username=email,password=pwd)#验证:返回验证对象,失败则是None,成功返回username
print("user:%s"%user)
if user:
login(req,user)
# next_url = req.GET.get("next", '../index')
# return redirect(next_url)
return redirect("/mytest/index/")
else:
error="账号或者密码错误"
return render(req, "acc_login.html",{'error':error})

def acc_logout(req):
logout(req)
return redirect("/mytest/login/")

@login_required()
def index(request):
context = {"key": "ok"}
return render(request,'index.html',context)



# 关于User model 密码,需要用 set_password
def test_create(req):
user = models.User(
username='jam',
nickname= 'jam'
)
user.set_password('1234')
return HttpResponse("ok")
posted @ 2019-08-05 10:38  东方不败--Never  阅读(1152)  评论(0编辑  收藏  举报