django简单实现注册登录模块
源码下载:https://files.cnblogs.com/files/hardykay/login.zip
新建项目(我使用pycharm开发,也可以使用如下命令建立项目 )
cmd命令行,前提需要安装django和配置系统环境变量,这里我就跳过了: django-admin startproject login 项目建好后通过cd 进入到项目目录执行以下命令: python manage.py startapp app01
需求分析
一个登录注册系统基本包含哪些功能呢?
1、首页
2、登录/注册页面
3、验证登录信息
4、验证注册信息
5、注销模块
概要设计
数据库设计ER图
urls.py文件
urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('registerView/', views.registerView), path('register/', views.register), path('login/', views.login), path('accounts/login/', views.logout), ]
setting.py文件
# 开发阶段放置项目自己的静态文件 STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'statics'), ) # 执行collectstatic命令后会将项目中的静态文件收集到该目录下面来(所以不应该在该目录下面放置自己的一些静态文件,因为会覆盖掉) STATIC_ROOT = os.path.join(BASE_DIR, 'static')
数据库设计
1、models.py
from django.db import models # Create your models here. class User(models.Model): username = models.CharField(max_length=50) email = models.CharField(max_length=60) password = models.CharField(max_length=20) def __str__(self): print(self.username)
2、建立数据库
# 1. 创建更改的文件 python manage.py makemigrations # 2. 将生成的py文件应用到数据库 python manage.py migrate
views.py功能模块设计
from django.shortcuts import render,HttpResponseRedirect from django.contrib import auth from app01.myform import User as FUser from app01.models import User from django.contrib.auth.decorators import login_required # Create your views here. def index(request): user = request.session.get('user',False) return render(request,'app01/index.html',{'user':user}) #显示页面 def registerView(request): user = request.session.get('user', False) print(user) if not user: return render(request, 'app01/login.html') else : return HttpResponseRedirect('/index/') #注册 def register(request): check = False if request.method == 'POST': form = FUser(request.POST) if form.is_valid(): #print(form.cleaned_data) user = User(**form.cleaned_data) user.save() check = True return render(request, 'app01/immediate.html',{'check':check}) return HttpResponseRedirect('/index/') #登录 def login(request): user = request.POST['username'] password = request.POST['password'] result = User.objects.get(username=user,password=password) if not result: return HttpResponseRedirect('/registerView/') else : request.session['user'] = user return HttpResponseRedirect('/index/') #注销 def logout(request): auth.logout(request) return HttpResponseRedirect('/index/')
首页模块设计(index函数)
def index(request): user = request.session.get('user',False) return render(request,'app01/index.html',{'user':user})
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% if not user %} <a href="/registerView/">注册/登录</a> {% else %} 您已经登录<a href="/accounts/login/">注销</a> {% endif %} </body> </html>
前后台是一起的,这里用了两个系统提供的功能模块:1、user = request.session.get('user',False)。2、return render(request,'app01/index.html',{'user':user})
1的作用是去键为user的session值,如果不存在则返回False,2的作用是将变量的值写入到模板,第二个参数是模板路径,第三个参数是需要渲染的字典。
登录/注册显示页面
def registerView(request): user = request.session.get('user', False) print(user) if not user: return render(request, 'app01/login.html') else : return HttpResponseRedirect('/index/')
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link href="/static/css/style.css" rel='stylesheet' type='text/css' /> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!--webfonts--> <!--//webfonts--> </head> <body> <div class="main"> <div class="header" > <h1>Login or Create a Free Account!</h1> </div> <p>Lorem iopsum dolor sit amit,consetetur sadipscing eliter,sed diam voluptua.At vero eso et accusam et justo duo dolores et ea rebum. </p> <form action="/register/" method="POST"> <ul class="left-form"> <h2>New Account:</h2> <li> <input type="text" name="username" placeholder="Username" required/> <a href="#" class="icon ticker"> </a> <div class="clear"> </div> </li> {% csrf_token %} <li> <input type="text" name="email" placeholder="Email" required/> <a href="#" class="icon ticker"> </a> <div class="clear"> </div> </li> <li> <input type="password" name="password" placeholder="password" required/> <a href="#" class="icon into"> </a> <div class="clear"> </div> </li> <li> <input type="password" placeholder="password" required/> <a href="#" class="icon into"> </a> <div class="clear"> </div> </li> <label class="checkbox"><input type="checkbox" name="checkbox" checked=""><i> </i>Please inform me of upcoming w3layouts, Promotions and news</label> <input type="submit" onClick="myFunction()" value="Create Account"> <div class="clear"> </div> </ul> </form> <form action="/login/" method="post"> <ul class="right-form"> {% csrf_token %} <h3>Login:</h3> <div> <li><input type="text" name="username" placeholder="Username" required/></li> <li> <input type="password" name="password" placeholder="Password" required/></li> <h4>I forgot my Password!</h4> <input type="submit" onClick="myFunction()" value="Login" > </div> <div class="clear"> </div> </ul> <div class="clear"> </div> </form> </div> <!-----start-copyright----> <div class="copy-right"> <p>Template 2014. More Templates <a href="http://www.cssmoban.com/" target="_blank" title="模板之家">模板之家</a> - Collect from <a href="http://www.cssmoban.com/" title="网页模板" target="_blank">网页模板</a></p> </div> <!-----//end-copyright----> </body> </html>
验证注册信息模块
1、建立form系统验证
from django import forms class User(forms.Form): username = forms.CharField(max_length=50) email = forms.CharField(max_length=60) password = forms.CharField(max_length=20)
2、后台代码
def register(request): check = False if request.method == 'POST': form = FUser(request.POST) if form.is_valid(): #print(form.cleaned_data) user = User(**form.cleaned_data) user.save() check = True return render(request, 'app01/immediate.html',{'check':check}) return HttpResponseRedirect('/index/')
验证登录信息模块
def login(request): user = request.POST['username'] password = request.POST['password'] result = User.objects.get(username=user,password=password) if not result: return HttpResponseRedirect('/registerView/') else : request.session['user'] = user return HttpResponseRedirect('/index/')
注销
def logout(request): auth.logout(request) return HttpResponseRedirect('/index/')