前提:能成功安装基础的Django
python .\manage.py startapp user
<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>
<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>
<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,redirect
from django.contrib.auth.models import User
from 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']=True
request.session['uname']=username
request.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 admin
from django.urls import path
from user.views import loginView,regView,index
urlpatterns = [
path('admin/', admin.site.urls),
path('login/',loginView),
path('reg/',regView),
path('index/',index),
]