django -- 登录验证

django -- 登录验证

环境说明

Django:1.10
Python:3.6

以 AbstractUser 方式扩展内置 User

# models.py 定义 model

from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.

class UserProfile(AbstractUser):
    # 昵称
    nick_name = models.CharField(max_length = 50, verbose_name = u"昵称", default="")
    

Note:内置 User 已经有了 username 和 password,要验证就是这两个

# admin.py 注册 model

from django.contrib import admin
from logre.models import UserProfile

admin.site.register(UserProfile)

authenticate 进行用户验证

Note: 值得注意的是,authenticate 只是一个验证而已,需要另外使用 login() 进行登录,加入 session 中保持登录状态,怎样获得这个 session 信息的话,有待学习

from django.shortcuts import render
from django.contrib import auth

def login(request):
	if request.method == 'POST':
		input_number = request.POST['input_username']
		input_pwd    = request.POST['input_pwd']

		# 匹配成功的话返回用户对象
		user = auth.authenticate(username=input_number,password=input_pwd)

		if user is not None and :
			# 更新登陆时间
			now_time        = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
			user.last_login = now_time
			user.save()
			
			auth.login(request,user)

			return render(request,'index.html')
	
	return render(request,'login.html')

上面判断中出现的 user.is_active,用来判断用户名密码是否有效

当然,另外的 html 页面和 url 配置这里就不多说明了

注销

既然说到登录,注销就在这里一并记录了

就像 login() 一样,auth 中也有 logout() 函数可以供我们使用

# views.py

from django.contrib import auth

def logout_view(request):
	auth.logout(request)
	return HttpResponseRedirect("/login/")

一样得配置相应的 url

常见问题

  1. 有时候,虽然数据库当中有 username 和 password 的存在,但是 authenticate 就是匹配不上,返回 None 值,可以尝试以下方法解决

使用django自带的auth.user类,我们在modles下自建的user下的账号,有时候authenticate()会读取不到;

在账号注册的时候,插入函数要弄对,要用objects.create_user()函数,你用objects.create插入的时明文的,authenticate()当然会读取不到

  1. 如果我们直接导入 auth 的 login 时,使用的使用为 login(request,user),当你的函数名恰好为 login(request) 就会出错,修改过来就好
login() takes 1 positional argument but 2 were given
原文地址:https://www.cnblogs.com/pinsily/p/7576963.html