心得:慢慢尝试和学习会有一定的结果的~生命里最重要的事情是要有个远大的目标,并借助才能与坚毅来完成它
我们在开发一个网站的时候,无可避免的需要设计实现网站的用户系统。此时我们需要实现包括用户注册、用户登录、用户认证、注销、修改密码等功能,这还真是个麻烦的事情呢。
Django作为一个完美主义者的终极框架,当然也会想到用户的这些痛点。它内置了强大的用户认证系统–auth,它默认使用 auth_user 表来存储用户数据。
1.authenticate()
提供了用户认证功能,即验证用户名以及密码是否正确,一般需要username 、password两个关键字参数。
如果认证成功(用户名和密码正确有效),便会返回一个 User 对象。
from django.contrib import auth
def index(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
obj = auth.authenticate(request,username=username,password=password)
from django.shortcuts import render,HttpResponse,redirect,reverse
from django.contrib import auth
from django.contrib.auth import authenticate, login,logout
from app01.forms import Reg,Login
def index(request):
login_obj=Login()
info=''
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
obj = auth.authenticate(request,username=username,password=password)
print(obj)
if obj:
info="登录成功"
login(request,obj)
return redirect(reverse('first'))
else:
info="登录失败,账号或者密码错误"
= return render(request,'index.html',context={"info":info,"login_obj":login_obj})
LOGIN_URL = '/login/' # 这里配置成你项目登录页面的路由
def logout_function(request):
logout(request)
return redirect(reverse('index'))
from django.contrib.auth.decorators import login_required
@login_required
def first(reqeust):
return render(reqeust,'first.html')
用来判断当前请求是否通过了认证。
def my_view(request):
if not request.user.is_authenticated():
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
from django.contrib.auth.models import User
user = User.objects.create_user(username='用户名',password='密码',email='邮箱',...)
from django.contrib.auth.models import User
user = User.objects.create_superuser(username='用户名',password='密码',email='邮箱',...)
auth 提供的一个检查密码是否正确的方法,需要提供当前请求用户的密码。
密码正确返回True,否则返回False。
用法:
ok = request.user.check_password(old_password)
request.user.set_password(new_password)
request.user.save()
from django.contrib.auth.models import AbstractUser
class UserInfo(AbstractUser):
"""
用户信息表
"""
nid = models.AutoField(primary_key=True)
phone = models.CharField(max_length=11, null=True, unique=True)
def __str__(self):
return self.username
forms.py
from django import forms
from django.forms import widgets
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
class Reg(forms.Form):
username = forms.CharField(
label="用户名",
min_length=4,
required=True,
)
password = forms.CharField(
label='密码',
min_length=6,
widget=widgets.PasswordInput()
)
re_password = forms.CharField(
label='确认密码',
min_length=6,
widget=widgets.PasswordInput()
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'})
def clean(self):
pwd = self.cleaned_data.get('password')
re_pwd = self.cleaned_data.get('re_password')
if pwd == re_pwd:
return self.cleaned_data
self.add_error('re_password', '两次密码不一致')
raise ValidationError('两次密码不一致')
class Login(forms.Form):
username = forms.CharField(
label="用户名",
min_length=4,
)
password = forms.CharField(
label='密码',
min_length=6,
widget=widgets.PasswordInput()
)
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index,name="index"),
url(r'^first/', views.first,name="first"),
url(r'^logout/', views.logout_function,name="logout"),
url(r'^register/', views.register,name="register"),
url(r'^change_pwd/', views.change_pwd,name="change_pwd"),
]
views.py
from django.shortcuts import render,HttpResponse,redirect,reverse
from django.contrib import auth
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from app01.forms import Reg,Login
def index(request):
login_obj=Login()
info=''
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
obj = auth.authenticate(request,username=username,password=password)
print(obj)
if obj:
info="登录成功"
login(request,obj)
return redirect(reverse('first'))
else:
info="登录失败,账号或者密码错误"
# User.objects.create_user(username=username,password=password)
return render(request,'index.html',context={"info":info,"login_obj":login_obj})
@login_required
def first(reqeust):
return render(reqeust,'first.html')
def logout_function(request):
logout(request)
return redirect(reverse('index'))
def register(request):
form_obj = Reg()
if request.method == "POST":
form_obj = Reg(request.POST)
if form_obj.is_valid():
username=form_obj.cleaned_data['username']
password=form_obj.cleaned_data['password']
User.objects.create_user(username=username,password=password)
print("注册成功")
return redirect(reverse('index'))
return render(request,'register.html',context={"form_obj":form_obj})
@login_required
def change_pwd(request):
error=''
if request.method=="POST":
old_password = request.POST.get('old_password')
new_password = request.POST.get('new_password')
confirm_password = request.POST.get('confirm_password')
print(old_password)
ok = request.user.check_password(old_password)
if ok:
print("旧密码正确")
error="旧密码正确"
if new_password:
if new_password == confirm_password:
request.user.set_password(new_password)
request.user.save()
print("修改密码成功")
error="修改密码成功"
return redirect(reverse('index'))
else:
print("两次密码不一致")
error="两次密码不一致"
else:
print("密码不能为空")
error="密码不能为空"
else:
error="旧密码错误"
return render(request,'change_pwd.html',context={"error":error})
index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="" method="post" >
{% csrf_token %}
{{ login_obj.as_p }}
<button>登录button>
<a href="{% url 'register' %}">注册a>
<p>{{ info }}p>
form>
body>
html>
register.html
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册title>
<link rel="stylesheet" href="{% static 'reg.css' %}">
head>
<body>
<div class="di">div>
<div class="container">
<div class="form">
<form action="" method="post" novalidate>
{% csrf_token %}
<div class="user">
<label for="{{ form_obj.username.id_for_label }}">用户名label>
{{ form_obj.username }}
div>
<span id="helpBlock2" class="help-block">{{ form_obj.password.errors.0 }}span>
<div class="pwd">
<label for="{{ form_obj.password.id_for_label }}">密码label>
{{ form_obj.password }}
div>
<span id="helpBlock2" class="help-block">{{ form_obj.password.errors.0 }}span>
<div class="re_pwd">
<label for="{{ form_obj.re_password.id_for_label }}">确认密码label>
{{ form_obj.re_password }}
div>
<span id="helpBlock2" class="help-block">{{ form_obj.re_password.errors.0 }}span>
<div class="button">
<button>注册button>
div>
<div>
<a href="{% url 'index' %}">返回a>
div>
form>
div>
div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js">script>
<script>
$('input').focus(function () {
$(this).next().text('').parent().parent().removeClass('help-block')
})
script>
body>
html>
first.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<p>第一个认证过的页面p>
<a href="{% url 'change_pwd' %}">修改密码a>
<a href="{% url 'logout' %}">注销登录a>
body>
html>
change_pwd.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改密码title>
head>
<body>
<p>修改密码p>
<form action="" method="post">
{% csrf_token %}
<p>原密码
<input type="text" name="old_password">
p>
<p>
新密码
<input type="text" name="new_password">
p>
<p>确认密码
<input type="text" name="confirm_password">
p>
<button>提交button>
<p> <a href="{% url 'first' %}">返回首页a>
p>
<h3>{{ error }}h3>
form>
body>
html>
reg.css
*{
margin:0;
padding:0;
}
.container{
width:1226px;
margin:75px auto;
}
.form{
width:500px;
margin:0 auto;
}
input{
width:210px;
height:20px;
padding:10px;
margin-top:20px;
font-size:40px;
}
label{
margin-right:30px;
font-size:25px;
}
button{
padding:15px;
}
.help-block{
margin-left:100px;
color:red;
font-size:15px;
}