python django-user模型(登陆,注册,密码修改,注销)

2022-12-08 18:15:02 来源:51CTO博客


(资料图)

{{ title }}

MyDjango Auth

{% if tips %}

{{ tips }}

{% endif %}

{% csrf_token %}

用户名:

密 码:

{% if new_password %}

新密码:

{% endif %}

用户登录

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):    # 设置标题和另外两个URL链接    title = "登录"    unit_2 = "/user/register.html"    unit_2_name = "立即注册"    unit_1 = "/user/setpassword.html"    unit_1_name = "修改密码"    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)                return redirect("/")            else:                tips = "账号密码错误,请重新输入"        else:            tips = "用户不存在,请注册"    return render(request, "user.html", locals())

# 用户注册

def registerView(request):    # 设置标题和另外两个URL链接    title = "注册"    unit_2 = "/user/login.html"    unit_2_name = "立即登录"    unit_1 = "/user/setpassword.html"    unit_1_name = "修改密码"    if request.method == "POST":        username = request.POST.get("username", "")        password = request.POST.get("password", "")        if User.objects.filter(username=username):            tips = "用户已存在"        else:            user = User.objects.create_user(username=username, password=password)            user.save()            tips = "注册成功,请登录"    return render(request, "user.html", locals())

# 修改密码

# 修改密码def setpasswordView(request):    # 设置标题和另外两个URL链接    title = "修改密码"    unit_2 = "/user/login.html"    unit_2_name = "立即登录"    unit_1 = "/user/register.html"    unit_1_name = "立即注册"    new_password = True    if request.method == "POST":        username = request.POST.get("username", "")        old_password = request.POST.get("password", "")        new_password = request.POST.get("new_password", "")        if User.objects.filter(username=username):            user = authenticate(username=username,password=old_password)            # 判断用户的账号密码是否正确            if user:                user.set_password(new_password)                user.save()                tips = "密码修改成功"            else:                tips = "原始密码不正确"        else:            tips = "用户不存在"    return render(request, "user.html", locals())                            

用户注销,退出登录

# 用户注销,退出登录def logoutView(request):    logout(request)    return redirect("/")

标签: 修改密码 另外两个 用户注销

上一篇:全球新消息丨Nginx之Keepalived高可用工具
下一篇:焦点精选!初识Druid分布式存储系统