1.解决使用系统自带登录功能时,出现403错误的方法,注释如下代码
djg3->settings->MIDDLEWSRE:
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 提交时必须注释
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
2.用户没登录时,访问需要登录才能访问的html时,默认跳转的路径
djg3->settings->末尾添加
LOGIN_URL='/user/login/'
3.users->urls.py
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from user import views
urlpatterns=[
# 登录
url(r'^login/',views.login,name='login'),
# 注册
url(r'^register/',views.register,name='register'),
# login_required 登录后才能使用的路由
# 首页
url(r'^index/',login_required(views.index),name='index'),
# 注销
url(r'^logout/',login_required(views.logout),name='logout'),
]
4.users->views.py
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.urls import reverse
from users.forms import UserForm, LoginForm
def register(request):
if request.method=='GET':
return render(request,'register.html')
if request.method=='POST':
#校验页面中传递的参数,是否填写完整
form = UserForm(request.POST)
#is_valid():判断表单验证是否通过
if form.is_valid():
# 获取校验后的用户和密码
username=form.cleaned_data.get('username')
password1 = form.cleaned_data.get('password1')
password2 = form.cleaned_data.get('password2')
# 判断密码是否相同
# 创建普通用户creat_user,创建超级管理员用户create_superuser
User.objects.create_user(username=username,password=password1)
# 实现跳转
return HttpResponseRedirect(reverse('users:login'))
else:
return render(request,'register.html',{'form':form})
def login(request):
if request.method=='GET':
return render(request,'login.html')
if request.method=='POST':
#表单验证,用户名和密码是否填写,校验用户名是否注册
form =LoginForm(request.POST)
if form.is_valid():
# 校验用户名和密码,判断返回的对象是否为空,如果不为空,则为user对象
user=auth.authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password'])
if user:
# 用户名和密码都是正确的,则登录
#进入登录状态,满足login_required要求
auth.login(request,user)
#跳转页面
return HttpResponseRedirect(reverse('users:index'))
else:
# 密码不正确
return render(request,'login.html',{'error':'密码错误'})
else:
return render(request,'login.html',{'form':form})
def index(request):
if request.method=='GET':
return render(request,'index.html')
def logout(request):
if request.method=='GET':
# 注销
#取消login_required的登录状态,进入未登录状态
auth.logout(request)
#跳转页面
return HttpResponseRedirect(reverse('users:login'))
5.users->forms
'''
导入规则顺序
1.新引入python自带的库
2.引入地方
3.引入自定义的
'''
from django import forms
from django.contrib.auth.models import User
class UserForm(forms.Form):
username=forms.CharField(required=True,
max_length=5,
min_length=2,
error_messages={
'required':'用户名必填',
'max_length':'用户名不能超过7个字符',
'min_length':'用户名至少两个字符'
})
password1=forms.CharField(required=True,
min_length=6,
error_messages={
'required':'密码必填',
'min_length':'密码不能少于6位'
})
password2=forms.CharField(required=True,
min_length=6,
error_messages={
'required':'确认密码必填',
'min_length':'确认密码不能少于6个'
})
def clean(self):
# 校验用户名是否已经注册过
user=User.objects.filter(username=self.cleaned_data.get('username'))
if user:
raise forms.ValidationError({'username':'用户名已存在'})
# 校验密码和确认密码是否相同
if self.cleaned_data.get('password1')!=self.cleaned_data.get('password2'):
raise forms.ValidationError({'password2':'两次密码不一致'})
return self.cleaned_data
class LoginForm(forms.Form):
username = forms.CharField(required=True,
max_length=5,
min_length=2,
error_messages={
'required': '用户名必填',
'max_length': '用户名不能超过7个字符',
'min_length': '用户名至少两个字符'
})
password = forms.CharField(required=True,
min_length=6,
error_messages={
'required': '密码必填',
'min_length': '密码不能少于6位'
})
def clean(self):
user = User.objects.filter(username=self.cleaned_data['username'])
if not user:
raise forms.ValidationError({'username': '用户名不存在,请注册'})
return self.cleaned_data
6.templates web页面
1)base.html 父模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
{% block title %}
{% endblock %}
</title>
</head>
{% block extCss %}
{% endblock %}
{% block extJs %}
{% endblock %}
<body>
{% block content %}
{% endblock %}
</body>
</html>
2)base_main.html 设置js
{% extends 'base.html' %}
{% block extJs %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"type="text/javascript"></script>
{% endblock %}
3)login 登录页面
{% extends 'base_main.html' %}
{% block title %}
登录
{% endblock %}
{% block content %}
<form action="" method="post">
{{form.errors.username}}
<p>姓名:<input type="text" name="username"></p>
{{form.errors.password}}
<p>密码:<input type="password" name="password"></p>
<input type="submit" value="登录">
</form>
{% endblock %}
4)register.html 注册页面
{% extends 'base_main.html' %}
{% block title %}
登录
{% endblock %}
{% block content %}
<form action="" method="post">
{{form.errors.username}}
<p>姓名:<input type="text" name="username"></p>
{{form.errors.password}}
<p>密码:<input type="password" name="password"></p>
<input type="submit" value="登录">
</form>
{% endblock %}
5)index.html 首页
{% extends 'base_main.html' %}
{% block title %}
首页
{% endblock %}
{% block content %}
<p>我是首页,需要登录才能访问</p>
<p><a href="{% url 'users:logout' %}">注销</a></p>
{% endblock %}