Django用户注册、登录、注销(一)

使用Django自带的用户认证系统编写认证、登录、注销基本功能

功能:

使用Django默认的User表

1)注册

  判断是否已存在此用户,存在的话提示报错“用户已存在”;

  判断两次输入的密码是否一致,不一致的话提示报错“密码不一致”。

 实现报错提示的方式有两种:

  第一种:在form表单中使用clean_函数进行定义判断函数,在views中进行的is_valid()判断时进行校验,并获取错误传送到模板中显示在前端。

  第二种:直接在views视图中判断

2)登录

  登录成功,跳转到主页index;

  登录不成功,初始化登录页面;

  跳转到注册页面。

3)主页

  直接访问主页,用户没有登录的话跳转到登录页面; 

  用户已登录显示用户登录名。

4)注销

  清除登录的session,退出登录

项目目录结构:

mysite/setting设置

注册应用:

更改时区和语言设置

from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
urlpatterns = [path('admin/', admin.site.urls),url(r'^djauth/',include('djauth.urls',namespace='djauth')),]
mysite/urls.py
from django.urls import re_path
from . import views
app_name='djauth'
urlpatterns=[re_path(r'^$',views.index),re_path(r'register/$',views.register,name="register"),re_path(r'login/$',views.login_view,name="login"),re_path(r'logout/$',views.logout_view,name="logout"),
]
djauth/urls.py
from django import forms
from django.contrib.auth.models import User
class login_form(forms.Form):username=forms.CharField(max_length=30)password=forms.CharField(widget=forms.PasswordInput)class register_form(forms.Form):username=forms.CharField(max_length=30,label="姓名")email=forms.EmailField()password=forms.CharField(widget=forms.PasswordInput,min_length=3,label="密码")password_re=forms.CharField(widget=forms.PasswordInput,min_length=3,label="确认密码")#第一种报错方式,使用form表单,views中捕捉##clean_字段,,在视图views使用is_valid时自动严重表单字段的有效性# def clean_username(self):#     cd=self.cleaned_data#     user=User.objects.filter(username=cd['username'])#     if user:#         raise forms.ValidationError('用户已存在')#     return cd['username']# def clean_password_re(self):#     cd=self.cleaned_data#     if cd['password']!=cd['password_re']:#         raise forms.ValidationError("密码不一致")#     return cd['password_re']
djauth/forms.py
from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
import time
from django.contrib import auth
from django.contrib.auth.models import User
from . import forms#访问index首页前先判断用户是否登录,没有登录的话需要跳转到login登录
#实现方式一:判断request.user.is_authenticated
# def index(request):
#     #验证用户是否登录成功
#     if  request.user.is_authenticated:
#         # request.user.username;;获取登录用户名
#         print("UserAuth:",request.user.username)
#         return render(request,"djauth/index.html")
#     else:
#         return redirect("/djauth/login/")
#实现方式二:使用@login_required装饰器
#login_required装饰器会先判断用户是否登录,如果没有登录则自动跳转到login_url路径,
#默认跳转路径是/accounts/login/,并在登录后跳转到原先的请求路径;如请求路径/djauth、,
#默认跳转路径为/accounts/login/?next=/djauth/#示例:
#没有login_url
#[13/Dec/2018 14:40:16] "GET /djauth/ HTTP/1.1" 302 0
#302跳转
#[13/Dec/2018 14:40:16] "GET /accounts/login/?next=/djauth/ HTTP/1.1"
#指定loging_url
#[13/Dec/2018 14:41:31] "GET /djauth/ HTTP/1.1" 302 0
#[13/Dec/2018 14:41:32] "GET /djauth/login/?next=/djauth/ HTTP/1.1" 200 725
#[13/Dec/2018 14:42:35] "POST /djauth/login/?next=/djauth/ HTTP/1.1" 302 0
#302登录成功后自动跳转
#[13/Dec/2018 14:42:35] "GET /djauth/ HTTP/1.1" 200 263
from django.contrib.auth.decorators import login_required
@login_required(login_url="/djauth/login/")
def index(request):return render(request,"djauth/index.html")def register(request):errors=[]if request.method=='POST':#初始化表单RegisterForm=forms.register_form(request.POST)#验证表单的输入是否有效,格式是否正确if RegisterForm.is_valid():# 第一种报错方式,捕捉form表单的报错##获取表单有效的值# Register=RegisterForm.cleaned_data##创建用户# user=User.objects.create_user(username=Register['username'],#                               password=Register['password'],#                               email=Register['email']#                               )##保存# user.save()# return HttpResponse("注册成功")##获取form表单clean函数中raise的错误#errors=RegisterForm.errors#第二种报错方式,直接在views中判断Register=RegisterForm.cleaned_data#判断用户是否存在user_exist=User.objects.filter(username=Register['username']).exists()if user_exist:errors.append("用户已存在")if Register['password']!=Register['password_re']:errors.append("密码不一致")else:user=User.objects.create_user(username=Register['username'],password=Register['password'],email=Register['email'])user.save()return HttpResponse("注册成功")#初始化表单RegisterForm=forms.register_form()return render(request,"djauth/register.html",{"RegisterForm":RegisterForm,"errors":errors})def login_view(request):error=[]curtime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())if request.method=='POST':LoginForm=forms.login_form(request.POST)if LoginForm.is_valid():Account=LoginForm.cleaned_data#验证User表中用户的账号密码是否正确,验证通过,返回用户名,不通过,返回Noneuser=auth.authenticate(username=Account['username'],password=Account['password'])if user is not None:#判断账户是否活跃if user.is_active:auth.login(request,user)return redirect("/djauth/")else:error.append("用户无效")else:error.append("账号或密码错误")else:LoginForm=forms.login_form()return render(request,'djauth/login.html',{"LoginForm":LoginForm,"curtime":curtime,"error":error})def logout_view(request):#清除session,登出
    auth.logout(request)return redirect("/djauth/login")
djauth/views.py
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
djauth/templates/djauth/base.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>首页</title>
</head>
<body>
<h1>首页</h1>
<!--获取登录用户名:request.user.username或user.username-->
{% if request.user.is_authenticated %}{{ user.username }}
{% endif %}<p><a href="{% url 'djauth:logout' %}">退出</a></p>
</body>
</html>
djauth/templates/djauth/index.html
{% extends "djauth/base.html" %}{% block title %}
Login Page
{% endblock %}{% block content %}
<h1>Login Page</h1>{% if error %}{{ error }}{% endif %}<p>时间:{{ curtime }}</p><form action="" method="post">{% csrf_token %}{{ LoginForm.as_p }}<input type="submit" value="Login"></form><p>没有账号?点击<a href="{% url 'djauth:register' %}">注册</a></p>
{% endblock %}
djauth/templates/djauth/login.html
{% extends "djauth/base.html" %}
{% block title %}
Register Page
{% endblock %}{% block content %}
<h1>Register Page</h1>{% if errors %}<p>{{ errors }}</p>{% endif %}<form action="" method="post">{% csrf_token %}{% for foo in RegisterForm %}<p>{{ foo.label_tag }}{{ foo }} {{ errors.foo }}</p>{% endfor %}<input type="submit" value="注册"></form>
{% endblock %}
djauth/templates/djauth/register.html

 

转载于:https://www.cnblogs.com/kikkiking/p/10113154.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/278684.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

如何在PowerPoint中自动调整图片大小

PowerPoint can automatically resize an image to fit a shape. You can also resize multiple images already in your presentation to all be the same size. Here’s how it works. PowerPoint可以自动调整图像大小以适合形状。 您还可以将演示文稿中已有的多个图像调整为…

如何在不支付Adobe Photoshop费用的情况下处理Camera Raw

You might think that you need expensive software to take advantage of Camera RAW—something like Photoshop or the more modestly priced Lightroom. Fortunately there is freeware that can help you achieve professional results without professional costs. 您可能…

eclipse 代码提示后面的百分比是什么意思?

简而言之&#xff0c;就是提示你其他人&#xff08;开发人员&#xff09;在此情形下使用该方法百分比&#xff0c;最常用方法百分比 见http://www.eclipse.org/recommenders/manual/#d0e32 Call Completion The Call Completion engine, for example, provides you with recomm…

travis-cli 使用

1. 添加项目登录 travis 选择对应项目即可 2. 添加持续集成文件.travis.ymllanguage: node_js node_js:- "node" before_install: - npm install -g jspm - jspm install script: - jspm bundle lib/main --inject备注&#xff1a;这是一个jspm 项目 3. 构建travis 是…

在Windows Media Center中收听超过100,000个广播电台

A cool feature in Windows 7 Media Center is the ability to listen to local FM radio. But what if you don’t have a tuner card that supports a connected radio antenna? The RadioTime plugin solves the problem by allowing access to thousands of online radio …

IntelliJ IDEA——数据库集成工具(Database)的使用

idea集成了一个数据库管理工具&#xff0c;可以可视化管理很多种类的数据库&#xff0c;意外的十分方便又好用。这里以oracle为例配置。 1、配置 在窗口的右边有个Database按钮&#xff0c;点击。 如果没有&#xff0c;请点击上方的View(视图)-Tool Windows(工具窗口)-Database…

代码评审会议_如何将电话会议(和访问代码)另存为联系人

代码评审会议Dialing a conference call doesn’t have to be a tedious process. Your iPhone or Android phone can automatically dial into the call and enter a confirmation code for you. You just have to create a special type of contact. 拨打电话会议不一定是一个…

使用iOS 4越狱iPhone或iPod Touch

In case you haven’t heard the news over the past couple of days, there is now an incredibly easy way to jailbreak your iPod Touch or iPhone running iOS 4. Here we will take a look at how easy the process is. 如果您在过去的几天里没有听到这个消息&#xff0c…

在Windows 7中禁用或修改Aero Peek的“延迟时间”

Are you looking for an easy way to modify the “delay time” for Aero Peek in Windows 7 or perhaps want to disable the feature altogether? Then see how simple it is to do either with the Desktop Peek Tweak. 您是否正在寻找一种简便的方法来修改Windows 7中Aer…

音频剪切_音频编辑入门指南:剪切,修剪和排列

音频剪切Audacity novices often start with lofty project ideas, but sometimes they lack the basics. Knowing how to cut and trim tracks is basic audio editing and is a fundamental starting point for making more elaborate arrangements. 大胆的新手通常从崇高的项…

搭建spring boot环境并测试一个controller

Idea搭建spring boot环境一、新建项目二、起步依赖三、编写SpringBoot引导类四、编写Controller五、热部署一、新建项目 1.新建project 2.选择SpringInitializr&#xff0c;选择jdk&#xff0c;没有则需要下载并配置(若选择Maven工程则需要自己添加pom.xml所需依赖坐标和Java…

音频噪声抑制_音频编辑入门指南:基本噪声消除

音频噪声抑制Laying down some vocals? Starting your own podcast? Here’s how to remove noise from a messy audio track in Audacity quickly and easily. 放下人声&#xff1f; 开始自己的播客&#xff1f; 这是在Audacity中快速轻松地消除杂乱音轨中噪声的方法。 Th…

Linux基础(day53)

2019独角兽企业重金招聘Python工程师标准>>> 12.21 php-fpm的pool php-fpm的pool目录概要 vim /usr/local/php/etc/php-fpm.conf//在[global]部分增加include etc/php-fpm.d/*.confmkdir /usr/local/php/etc/php-fpm.d/cd /usr/local/php/etc/php-fpm.d/vim www.co…

Mysql+Navicat for Mysql

一、mysql 1.下载安装 Mysql官网下载地址 下载后解压 .zip &#xff08;或安装.msi&#xff09; 2.可加入全局变量mysqld &#xff08;可选&#xff09; 我的电脑->属性->高级->环境变量->Path(系统变量)&#xff0c;添加mysql下的bin目录&#xff0c;如 D:\Pr…

公钥,私钥和数字签名

一、公钥加密 假设一下&#xff0c;我找了两个数字&#xff0c;一个是1&#xff0c;一个是2。我喜欢2这个数字&#xff0c;就保留起来&#xff0c;不告诉你们(私钥&#xff09;&#xff0c;然后我告诉大家&#xff0c;1是我的公钥。 我有一个文件&#xff0c;不能让别人看&…

MySQL中的日志类型(二)-General query log

简介 General query log记录客户端的连接和断开&#xff0c;以及从客户端发来的每一个SQL语句。 日志内容格式 General query log可以记录在文件中&#xff0c;也可以记录在表中&#xff0c;格式如下&#xff1a;在文件中会记录时间、线程ID、命令类型以及执行的语句示例如下&a…

android wi-fi_如何在Android手机上查找3G或Wi-Fi速度

android wi-fiAre you curious about what kind of connection speed you are getting with your Android phone? Today we’ll take a look at how to easily check your Wi-Fi or 3G speeds with Speedtest.net’s Speed Test app. 您是否对Android手机的连接速度感到好奇&a…

如何在Gmail的图片中插入超链接

Adding hyperlinks is an efficient way of getting your reader to the intended web page. Though it’s no secret that you can add hyperlinks to text, Gmail also lets you add hyperlinks to images in the body of the email. Here’s how to make it happen. 添加超链…

新垣结衣自拍照_如何阻止自拍照出现在iPhone的自拍照专辑中

新垣结衣自拍照Khamosh PathakKhamosh PathakThe Photos app on your iPhone automatically populates all photos from the front-facing camera in the Selfies album. But what if you don’t want a photo to appear there? Here are a couple of solutions. iPhone上的“…

如何设置自定义任务栏图标_如何为任何应用程序自定义Windows 7任务栏图标

如何设置自定义任务栏图标Would you like to change out the icons on your taskbar with a beautiful set of icons that all go together? Here’s how you can change out the random candy-colored icons for a stylish icon set of your choice. 您是否要用一组漂亮的图…