首页 > 编程 > Python > 正文

django的登录注册系统的示例代码

2020-02-23 00:07:06
字体:
来源:转载
供稿:网友

摘要

django框架本身自带有登录注册,也可以自己写登录注册,下面将介绍这这2种方式实登录注册

一、自己写登录注册登出

1.注册regist

注册采用的是form表单,提交到数据库,在登录的时候,查询数据看,看用户有没有注册,如果用户没有注册,则返回注册页面注册

(1)models.py文件里创建相关的字段: 用户名字/用户密码/cookies携带的ticket

from django.db import models# Create your models here.class Users(models.Model):  u_name = models.CharField(max_length=10)  u_password = models.CharField(max_length=255)  u_ticket = models.CharField(max_length=30, null=True)  class Meta:    db_table = 'day51_user'

(2)urls.py 配置相关路由

from django.conf.urls import urlfrom uauth import viewsurlpatterns = [  url(r'^regist/', views.regist),  url(r'^login/', views.login),  url(r'^logout', views.logout)]

(3)views.py 书写regist方法

导入相关的包,在regist,login,logout都会使用到

import randomimport timefrom django.contrib import authfrom django.contrib.auth.hashers import make_password,check_passwordfrom django.contrib.auth.models import Userfrom django.http import HttpResponseRedirect, HttpResponsefrom django.shortcuts import renderfrom django.core.urlresolvers import reverse# Create your views here.from uauth.models import Users

如果用户请求regist方法,则直接跳转到相关的html页面。

如果用户在html页面点击了post按钮,对密码进行加密后,将数据提交到数据库,并返回登录login页面。

获得post提交的表单文字,使用request.POST.get(' ')

def regist(request):  if request.method == 'GET':    return render(request, 'day6_regist.html')  if request.method == 'POST':    # 注册    name = request.POST.get('name')    password = request.POST.get('password')    # 对密码进行加密    password = make_password(password)    Users.objects.create(u_name=name, u_password=password)    return HttpResponseRedirect('/uauth/login/')

编写regist的提交表单, method方法选择'POST'

文件目录在templates下[图片上传中...(image.png-cc7763-1526105439415-0)]

{%csrf_token%}是针对提交的时候csrf跨域错误

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>注册页面</title></head><body><form action="" method="POST">  {% csrf_token %}  注册姓名:<input type="text" name="name">  注册密码:<input type="password" name="password">  <input type="submit" value="提交"></form></body></html>

2.登录login

(1)配置路由urls.py, 与注册的时候一样的操作

(2)配置views.py, 编写login方法

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表