Django6 登录认证

settings

# 必须的
AUTH_USER_MODEL = 'App.User'
# 登录页面地址
LOGIN_URL = '/login/'

urls

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include("App.urls")),
]

App.urls

from django.urls import path
from App import views

app_name = "App"
urlpatterns = [
    path("",views.index, name='index'),
    path('userregister/', views.user_register, name='user_register'),
    path('login/',views.user_login,name='login'),
    path('logout/',views.user_logout,name='logout'),
    path('publish/',views.publish_article,name='publish'),
    path('change/',views.change_password,name='change'),
]

App.views

from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse

from App.forms import RegisterForm
from App.models import User

def user_register(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            data.pop("confirm")
            # 把用户写入数据库
            # 密码会做签名,不能手动签名加密password
            user = User.objects.create_user(**data)
            if user:
                return HttpResponse("注册成功")
            else:
                return render(request, "register.html",{'form':form})
        else:
            return render(request, "register.html", {'form': form})
    # get请求
    return render(request, "register.html")


def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username','')
        password = request.POST.get('password','')

        # 用户验证,如果用户名和密码正确,返回User的对下,否则返回None
        user = authenticate(request,username=username,password=password)
        if user:
            # 记录用户登录状态,参数是请求对象和用户对象
            login(request,user)

            return redirect(reverse("App:index"))
        else:
            return render(request,'login.html',{'msg':'用户名和密码错误'})
    return render(request,'login.html')


def user_logout(request):
    # 退出登录
    logout(request)
    return redirect(reverse("App:index"))


def index(request):
    # 在后端判断是否登录
    print(request.user.is_authenticated)
    return render(request,'index.html')

# 路由保护
@login_required
def publish_article(request):
    return HttpResponse("发表文章")


def change_password(request):
    # 修改密码
    user = User.objects.get(pk=1)
    user.set_password('123')
    user.save()
    return HttpResponse("修改密码")

App.forms

from django import  forms
from django.core.exceptions import ValidationError


class RegisterForm(forms.Form):
    username = forms.CharField(min_length=3,required=True,error_messages={
        'required':'用户名必须输入',
        'min_length':'用户名至少3个字符'
    })
    password = forms.CharField(min_length=3,required=True,error_messages={
        'required': '密码名必须输入',
        'min_length': '密码至少3个字符'
    })
    confirm = forms.CharField(min_length=3,required=True,error_messages={
        'required': '密码名必须输入',
        'min_length': '密码至少3个字符'
    })
    regtime = forms.DateTimeField(required=False,error_messages={
        'invalid':'日期格式错误',
    })
    sex = forms.BooleanField(required=False)

    # 单个字段验证: clean_xxxx
    def clean_password(self):
        password = self.cleaned_data.get('password')
        if password and password.isdigit():
            raise ValidationError("密码不能是纯数字")
        return password


    # 全局验证
    def clean(self):
        password = self.cleaned_data.get('password',None)
        confirm = self.cleaned_data.get('confirm','')
        print(password,confirm)
        if password != confirm:
            raise ValidationError({'confirm':"两次密码输入不一致"})
        return self.cleaned_data

App.models

from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    uid = models.AutoField(primary_key=True)
    username = models.CharField(unique=True, max_length=30)
    password = models.CharField(max_length=128)
    regtime = models.DateTimeField()
    sex = models.IntegerField(blank=True, null=True)

    class Meta:
        db_table = 'user'

register.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册title>
head>
<body>
<form action="{% url 'App:user_register' %}" method="post">
    {% csrf_token %}
    用户名:<input type="text" name="username">
    {% for error in form.username.errors %}
        <span>{{ error }}span>
    {% endfor %}
    <br>
    密码:<input type="password" name="password">
    {{ form.password.errors }}
    <br>
    确认密码:<input type="password" name="confirm">
     {{ form.confirm.errors }}
    <br>
    注册时间:<input type="text" name="regtime">
     {{ form.regtime.errors }}
    <br>
    性别:<input type="radio" name="sex" value="0"><input type="radio" name="sex" value="1"> 男
     {{ form.sex.errors }}
    <br>
    <input type="submit" value="注册">
form>
body>
html>

login.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录title>
head>
<body>
<h2>{{ msg }}h2>
<form action="{% url 'App:login' %}" method="post">
    {% csrf_token %}
    用户名:<input type="text" name="username"> <br>
    密码:<input type="password" name="password"> <br>
    <input type="submit" value="登录">
form>
body>
html>

index.html


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
{% if request.user.is_authenticated %}
    {{ request.user.username }}  <a href="{% url 'App:logout' %}">退出登录a>
{% else %}
    你还没有登录,请先 <a href="{% url 'App:login' %}">登录a>
{% endif %}
body>
html>

连接数据库,创建用户管理库

python manage.py makemigrations
python manage.py migrate

你可能感兴趣的:(5-web,数据库,python,django,mysql)