博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django 快速实现完整登录系统(cookie)
阅读量:4577 次
发布时间:2019-06-08

本文共 5153 字,大约阅读时间需要 17 分钟。

本操作的环境:

===================

deepin linux 2013(基于ubuntu)

python 2.7

Django 1.6.2

===================

 

创建项目与应用                                                                                     

 

#创建项目fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite5fnngj@fnngj-H24X:~/djpy$ cd mysite5#在项目下创建一个online应用fnngj@fnngj-H24X:~/djpy/mysite5$ python manage.py startapp online

目录结构如下:

打开mysite5/mysite5/settings.py文件,将应用添加进去:

# Application definitionINSTALLED_APPS = (    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'online',)

 

 

设计数据库                                                                                              

 

打开mysite5/online/models.py文件,添加如下内容:

from django.db import models# Create your models here.class User(models.Model):    username = models.CharField(max_length=50)    password = models.CharField(max_length=50)    def __unicode__(self):        return self.username

创建数据库,创建User表,用户名和密码两个字段。

下面进行数据库的同步:

fnngj@fnngj-H24X:~/djpy/mysite5$ python manage.py syncdbCreating tables ...Creating table django_admin_logCreating table auth_permissionCreating table auth_group_permissionsCreating table auth_groupCreating table auth_user_groupsCreating table auth_user_user_permissionsCreating table auth_userCreating table django_content_typeCreating table django_sessionCreating table online_userYou just installed Django's auth system, which means you don't have any superusers defined.Would you like to create one now? (yes/no): yes   输入yes/noUsername (leave blank to use 'fnngj'):     用户名(默认当前系统用户名)Email address: fnngj@126.com     邮箱地址Password:    密码Password (again):    确认密码Superuser created successfully.Installing custom SQL ...Installing indexes ...Installed 0 object(s) from 0 fixture(s)

最后生成的 online_user 表就是我们models.py 中所创建的User类。

 

 

配置URL                                                                                                  

 

打开mysite5/mysite5/urls.py:

from django.conf.urls import patterns, include, urlfrom django.contrib import adminadmin.autodiscover()urlpatterns = patterns('',    # Examples:    # url(r'^$', 'mysite5.views.home', name='home'),    url(r'^admin/', include(admin.site.urls)),    url(r'^online/', include('online.urls')),)

 

在mysite5/online/目录下创建urls.py文件:

from django.conf.urls import patterns, urlfrom online import views urlpatterns = patterns('',    url(r'^$', views.login, name='login'),    url(r'^login/$',views.login,name = 'login'),    url(r'^regist/$',views.regist,name = 'regist'),    url(r'^index/$',views.index,name = 'index'),    url(r'^logout/$',views.logout,name = 'logout'),)

 

    登陆页

  登陆页

   注册页

    登陆成功页  

   注销

 

 

创建视图                                                                                                  

 

打开mysite5/online/views.py 文件:

#coding=utf-8from django.shortcuts import render,render_to_responsefrom django.http import HttpResponse,HttpResponseRedirectfrom django.template import RequestContextfrom django import formsfrom models import User#表单class UserForm(forms.Form):     username = forms.CharField(label='用户名',max_length=100)    password = forms.CharField(label='密码',widget=forms.PasswordInput())#注册def regist(req):    if req.method == 'POST':        uf = UserForm(req.POST)        if uf.is_valid():            #获得表单数据            username = uf.cleaned_data['username']            password = uf.cleaned_data['password']            #添加到数据库            User.objects.create(username= username,password=password)            return HttpResponse('regist success!!')    else:        uf = UserForm()    return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req))#登陆def login(req):    if req.method == 'POST':        uf = UserForm(req.POST)        if uf.is_valid():            #获取表单用户密码            username = uf.cleaned_data['username']            password = uf.cleaned_data['password']            #获取的表单数据与数据库进行比较            user = User.objects.filter(username__exact = username,password__exact = password)            if user:                #比较成功,跳转index                response = HttpResponseRedirect('/online/index/')                #将username写入浏览器cookie,失效时间为3600                response.set_cookie('username',username,3600)                return response            else:                #比较失败,还在login                return HttpResponseRedirect('/online/login/')    else:        uf = UserForm()    return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))#登陆成功def index(req):    username = req.COOKIES.get('username','')    return render_to_response('index.html' ,{'username':username})#退出def logout(req):    response = HttpResponse('logout !!')    #清理cookie里保存username    response.delete_cookie('username')    return response

这里实现了所有注册,登陆逻辑,中间用到cookie创建,读取,删除操作等。

 

 

创建模板                                                                                                  

 

先在mysite5/online/目录下创建templates目录,接着在mysite5/online/templates/目录下创建regist.html 文件:

注册

注册页面:

{% csrf_token %} {
{uf.as_p}}
登陆

mysite5/online/templates/目录下创建login.html 文件:

登陆

登陆页面:

{% csrf_token %} {
{uf.as_p}}
注册

mysite5/online/templates/目录下创建index.html 文件:

welcome {
{username}} !

退出

 

设置模板路径

打开mysite5/mysite5/settings.py文件,在底部添加:

#templateTEMPLATE_DIRS=(    '/home/fnngj/djpy/mysite5/online/templates')

 

 

使用功能                                                                                                  

 

注册

先注册用户:

注册成功,提示“regist success!!”

 

登陆

执行登陆操作,通过读取浏览器cookie 来获取用户名

 

查看cookie

 

登陆成功

通过点击“退出”链接退出,再次访问 将不会显示用户名信息。

转载于:https://www.cnblogs.com/frchen/p/5710675.html

你可能感兴趣的文章
PhpExcel中文帮助手册|PhpExcel使用方法
查看>>
Linux下安装rpm出现error: Failed dependencies
查看>>
Chapter 6 排序
查看>>
通用的运营商/数字在C#
查看>>
7kyu Jaden Casing Strings
查看>>
主流编程语言的大概方向(个人理解)
查看>>
2015 HUAS Provincial Select Contest #1 A
查看>>
逆向工程——注册篇
查看>>
Python3 集合(无序的set)
查看>>
推荐10款免费的在线UI测试工具
查看>>
解构控制反转(IoC)和依赖注入(DI)
查看>>
燕十八redis 微博地址
查看>>
面向对象的特征有哪些方面?
查看>>
三月十一号
查看>>
OpenCV_累加一个三通道矩阵中的所有元素
查看>>
差点搞不懂快排
查看>>
STM32学习之路入门篇之指令集及cortex——m3的存储系统
查看>>
Linux 任务计划:crontab
查看>>
JPA用法中字段起名规范
查看>>
http status code
查看>>