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,一经查实,立即删除!

相关文章

1月3日学习内容整理:modelform

1、modelform本质上还是form组件 2、引入 from django.forms import ModelForm 3、创建 class Form(ModelForm): class Meta: modelBook Book就是models.py中定义的类&#xff0c;也就是表 firelds"_ _all_ _" 代表继承Book表中的所有字…

如何在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可以自动调整图像大小以适合形状。 您还可以将演示文稿中已有的多个图像调整为…

vue目录结构

vue目录结构参考一参考二参考三参考一 目录一级二级bulid项目构建的一些 js 文件config配置文件项&#xff0c;index.js 比较重要&#xff0c;打包上线需要修改配置dist项目打包后的文件node_modulesnpm安装包位置src项目的开发目录-assets图片、字体等资源-components公共组件…

js获取当前日期

var myDate new Date(); myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); //获取完整的年份(4位,1970-????) myDate.getMonth(); //获取当前月份(0-11,0代表1月) myDate.getDate(); //获取当前日(1-31) myDate.getDay(); //获取当前星期X(0-6,0代表星期天) …

如何在不支付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…

python实现关联规则

代码中Ci表示候选频繁i项集&#xff0c;Li表示符合条件的频繁i项集    # codingutf-8    def createC1(dataSet): # 构建所有1项候选项集的集合    C1 []    for transaction in dataSet:    for item in transaction:    if [item] not in C1:   …

Progressive Web App(PWA)

Progressive Web App一、 PWA 宣传 &#xff1a; Reliable &#xff08; 可靠的 &#xff09;、Fast&#xff08; 快速的 &#xff09;、Engaging&#xff08; 可参与的 &#xff09;二、什么是Progressive三、为什么我们需要Progressive Web App一、 PWA 宣传 &#xff1a; Re…

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 …

vue项目中按需引入viewUI

viewUI一、按需引入二、忽略eslint编译器检测和编译检测1.忽略编译器检测2.编译器中忽略一、按需引入 npm install babel-plugin-import --save-dev // .babelrc1 { “plugins”: [[“import”, { “libraryName”: “view-design”, “libraryDirectory”: “src/components”…

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

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

为什么VC经常输出烫烫烫烫烫烫烫烫

在Debug 模式下&#xff0c; VC 会把未初始化的栈内存全部填成0xcc&#xff0c;当字符串看就是 烫烫烫烫……会把未初始化的堆内存全部填成0xcd&#xff0c;当字符串看就是 屯屯屯屯……可以让我们方便地看出那些内存没初始化但是Release 模式下不会有这种附加动作&#xff0c;…

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

代码评审会议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. 拨打电话会议不一定是一个…

Vuex使用总结

Vuex综合使用一、仓库1.主仓库2.子仓库二、使用1.全局&#xff08;index.js和未开启命名空间的子仓库&#xff09;2.子仓库&#xff08;子仓库定义了namespaced: true&#xff09;&#xff0c;仓库名&#xff1a;home3.使用strict严格模式&#xff08;建议&#xff09;三、批量…

好未来提前批

好未来提前批(注&#xff1a;转载于牛客网) 一面&#xff08;25minutes&#xff09; 1.创建对象的几种方式2.Jsp九大隐式对象3.自己封装的持久层框架用过么4.Spring ioc让你实现怎么实现呢&#xff08;工厂反射&#xff0c;我半年前写过&#xff0c;忘记了&#xff09;5.Aop的实…

Nginx服务学习(6)-日志模块

日志模块的说明 日志的默认路径&#xff1a;error_log /var/log/nginx/error.log warn; warn是指日志的等级&#xff0c;一般有debug, info, notice, warn, error, crit。access_log /var/log/nginx/access.log main; main是指访问日志记录的格式信息&#xff0c;在…

vue mock模拟后台接口数据

vue mock一、Json server二、Mock 服务1.安装2.创建 Mock3.main.js引入4.组件中axure请求一、Json server 轻量级&#xff0c;将已有的json文件跑在服务器上供前端调用 npm install -g json-server 启动JSON数据服务器&#xff1a; json-server --watch json文件名 或 json-se…

个人站立会议-----20181216

继续阅读测量程序设计这本书&#xff0c;并根据测量平差基础中的知识编写多个已知点水准网的间接平差&#xff0c;结果总是差些&#xff0c;询问过老师之后&#xff0c;才知道在程序中要增加检索闭合欢或闭合线段的条件&#xff0c;正在改进中 转载于:https://www.cnblogs.com/…

使用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…