能成功登录和注册并实现页面之间的跳转
前提:能成功安装基础的Django
创建应用并添加到项目中
python .\manage.py startapp user
创建存放模板的目录并添加到项目中
欢迎界面
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>陈十一yi的主页</title></head><body><h1>欢迎登录</h1><h3>您好!欢迎您,{{name}}</h3></body></html>
用户登录界面
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>陈十一yi-用户登录</title></head><body><form method="POST" action="/login/">{%csrf_token%} 用户名:<input type="text" name="username" /><br/> <br/> 密 码:<input type="password" name="password" /><br/><button type="submit">登录</button> <a href="/reg/">注册新用户</a>{{ msg }}</form></body></html>
注册界面
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>用户注册</title></head><body><form method="POST" action="/reg/">{%csrf_token%} 用户名:<input type="text" name="username" /><br/>密 码:<input type="password" name="password" /><br/> 邮 箱:<input type="text" name="email" /><br/><button type="submit">注册</button> {{ msg }}</form></body></html>
定义视图
from django.shortcuts import render,redirectfrom django.contrib.auth.models import Userfrom django.contrib.auth import login,logout,authenticate# Create your views here.#登录def loginView(request):if request.method=="POST":username=request.POST.get("username")password=request.POST.get("password")if User.objects.filter(username=username):user=authenticate(username=username,password=password)if user:if user.is_active:login(request,user)# msg="登录成功"request.session['status']=Truerequest.session['uname']=usernamerequest.session.set_expiry(300)return redirect("/index/")else: msg="用户名密码错误"else:msg="用户名不存在"return render(request,"login.html",locals()) #注册def regView(request):if request.method=="POST":username=request.POST.get("username")password=request.POST.get("password")email=request.POST.get("email")if User.objects.filter(username=username):msg="用户名已存在"else:user=User.objects.create_user(username=username,password=password,email=email)msg="注册成功"return redirect("/login/")return render(request,"register.html",locals())##主页def index(request):return render (request,"index.html",{"name":request.session.get('uname')})
添加路由
from django.contrib import adminfrom django.urls import pathfrom user.views import loginView,regView,indexurlpatterns = [path('admin/', admin.site.urls),path('login/',loginView),path('reg/',regView),path('index/',index),]
验证
web登录127.0.0.1:8000/login
用创建的用户没有点注册即可创建用户
注册新用户
登录新用户