任务描述:实现登录和退出

1.项目结构

2.源代码

urls.py

from django.conf.urls import url
from django.contrib import admin
from user import views admin.autodiscover() urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'index/', views.index),
url(r'user/regist/', views.regist),
url(r'user/login/', views.login),
url(r'user/logout/', views.logout),
]

views.py

from django.shortcuts import render
from django import forms
from django.http import HttpResponseRedirect, HttpResponse
import sqlite3
from . import models class UserForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
headimg = forms.FileField() class LoginForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput) def insert(user):
# 连接数据保存
models.User.objects.create(username=user.username, password=user.password, headimg=user.headimg)
return True def find_user(user):
users = models.User.objects.filter(username=user.username, password=user.password)
if users:
return True
else:
return False def regist(request):
context = {}
if request.method == 'POST':
uf = UserForm(request.POST, request.FILES)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
headimg = uf.cleaned_data['headimg']
user = models.User(username=username, headimg=headimg.name, password=password)
# save headimg
fp = open('upload/' + headimg.name, 'wb')
s = headimg.read()
fp.write(s)
fp.close()
if insert(user):
return HttpResponseRedirect('/user/login') # 重定向到登录界面
else:
uf = UserForm()
context = {'uf': uf}
return render(request, 'user/regist.html', context) def login(request):
context = {}
if request.method == 'POST':
uf = LoginForm(request.POST)
if uf.is_valid():
username = uf.cleaned_data['username']
password = uf.cleaned_data['password']
user = models.User(username=username, password=password)
if find_user(user):
print('find it!')
# session
request.session['username'] = username
response = HttpResponseRedirect('/index/')
# cookie
# response.set_cookie('username', username, 3600) # 将username写入浏览器cookie,失效时间为3600
response.set_cookie('password', password, 3600) # 将password写入浏览器cookie,失效时间为3600
return response
else:
return render(request,'/user/login/',context)
else:
uf = LoginForm()
print('not find it!')
context = {'uf': uf}
return render(request, 'user/login.html', context) def logout(request):
response = HttpResponseRedirect('/user/login/')
try:
del request.session['username']
except Exception as e:
print(e)
# response.delete_cookie('username')
response.delete_cookie('password') # 删除cookie
return response def index(request):
context = {}
# session
username = request.session.get('username', 'anybody')
context['username'] = username
# cookie
if request.COOKIES:
print(request.COOKIES)
return render(request, 'index.html', context)

index,html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h2>This is index page!</h2>
<p>welcome,{{username}} !</p>
<a href="/user/logout/">Logout</a>
</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form method="post" action="/user/login/">
{% csrf_token %}
{{uf.as_p}}
<input type="submit" value="submit">
</form>
</body>
</html>

regist.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>regist</title>
</head>
<body>
<h3>regist</h3>
<hr>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{uf.as_p}}
<input type="submit" value="submit">
</form>
</body>
</html>

models.py

from django.db import models

class User(models.Model):
username = models.CharField(max_length=100)
password = models.CharField(max_length=20, default='123456')
headimg = models.FileField() def __str__(self):
return self.username + ',' + self.password + ',' + self.headimg.name

3.运行测试

未登录访问:

登录后访问:

退出

Django会话cookie&session的更多相关文章

  1. day09 Django: 组件cookie session

    day09 Django: 组件cookie session   一.cookie和session都是会话跟踪技术     1.什么是会话             可以理解为客户端和服务端之间的一次会 ...

  2. django - 总结 - cookie|session

    Cookie是通过HTTP请求和响应头在客户端和服务器端传递的. 在Web开发中,使用session来完成会话跟踪,session底层依赖Cookie技术. --------------------- ...

  3. python框架之Django(7)-Cookie&Session使用

    Cookie 添加 response.set_cookie 添加明文cookie response.set_cookie(key, value='', max_age=None, expires=No ...

  4. python 全栈开发,Day76(Django组件-cookie,session)

    昨日内容回顾 1 json 轻量级的数据交换格式 在python 序列化方法:json.dumps() 反序列化方法:json.loads() 在JS中: 序列化方法:JSON.stringfy() ...

  5. Django中cookie&session的实现

    1.什么叫Cookie Cookie翻译成中文是小甜点,小饼干的意思.在HTTP中它表示服务器送给客户端浏览器的小甜点.其实Cookie是key-value结构,类似于一个python中的字典.随着服 ...

  6. Django之cookie+session

    前言 HTTP协议 是短连接.且状态的,所以在客户端向服务端发起请求后,服务端在响应头 加入cokie响应给浏览器,以此记录客户端状态: cook是来自服务端,保存在浏览器的键值对,主要应用于用户登录 ...

  7. Django之cookie&session

    cookie Cookie 是在 HTTP 协议下,服务器或脚本可以维护客户工作站上信息的一种方式.Cookie 是由 Web 服务器保存在用户浏览器(客户端)上的小文本文件,它可以包含有关用户的信息 ...

  8. django框架--cookie/session

    目录 一.http协议无状态问题 二.会话跟踪技术--cookie 1.对cookie的理解 2.cookie的使用接口 3.cookie的属性 4.使用cookie的问题 三.会话跟踪技术--ses ...

  9. Django组件-cookie,session

    昨日内容回顾: json 轻量级的数据交换格式 在python 序列化方法:json.dumps() 反序列化方法:json.loads() 在JS中: 序列化方法:JSON.stringfy() 反 ...

随机推荐

  1. java 矩阵求逆

    package com.yang.matrix; public class TestMatrix { public static void main(String[] args) { // 测试数据 ...

  2. Navicat for MySQL 新建查询时,报can't create file ...系统找不到指定的文件夹出现问题

    如图点击新建查询报错 解决办法 将这个路径修改一下就ok了

  3. windows7下安装Office2010提示需要安装MSXML6.10.1129

    平台:Windows 7 问题:刚刚下载的ghost Win 7,安装过程一切顺利,进入系统后把集成的软件全部卸载,清理完垃圾,安装了VC库,在安装Office2010时提示需要安装MSXML6.10 ...

  4. js全选反选按钮实现

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  5. Django快速搭建博客

    准备工作: 1.Python 2.Django 3.Git 安装Python: 官网下载 安装Django: #安装最新版本的Django $ pip install django #或者指定安装版本 ...

  6. LiveReload配置,安装使用方法~~~前端页面神助手

    一.Chrome端安装LiveReload插件 1.首先这里啰嗦一下,如果Chrome无法进入商店,可以先安装一下谷歌商店助手 谷歌商店插件地址 http://pan.baidu.com/s/1dF1 ...

  7. 洛谷 P3669 [USACO17OPEN]Paired Up 牛牛配对

    P3669 [USACO17OPEN]Paired Up 牛牛配对 题目描述 Farmer John finds that his cows are each easier to milk when ...

  8. @property 和@synthesize

    xcode4.4之后,@property包括了@synthesize的功能. 这是编译器的升级. @property有几个作用:1)默认生成一个私有成员变量,并有一个带下划线的别名如_age   2) ...

  9. wechat4j框架具体解释

    发送消息: 基于上面access_token的逻辑,在构造发送消息对象的时候请依照例如以下代码. wechat4j和微信强力推荐的方法 CustomerMsg customerMsg = new Cu ...

  10. poi完美word转html(表格、图片、样式)

    直入正题,需求为页面预览word文档,用的是poi3.8,以下代码支持表格.图片,不支持分页,只支持doc,不支持docx: /** * */ import java.io.BufferedWrite ...