请求与相应
HttpRequest对象API
def home(request):
print('path:', request.path)
print('mothod:', request.method)
print('encoding:', request.encoding)
print('GET:', request.GET)
print('POST:', request.POST)
print('FILES', request.FILES)
print('COOKIES:', request.COOKIES)
print('session:', request.session)
print('is_ajax:', request.is_ajax()) path: /blog1/home/
mothod: GET
encoding: None
GET: <QueryDict: {}>
POST: <QueryDict: {}>
FILES <MultiValueDict: {}>
COOKIES: {'csrftoken': 'xnjakTTg7c8cy6pnyZzgKg8fkyXkMBcl3LXCnMeQC8n4oLIByU0U6Pr3DGCRj6EO', 'sessionid': '7it5s9n3zn8or27i9kxqiewjiq6rvjfb'}
session: <django.contrib.sessions.backends.db.SessionStore object at 0x7fbcd958f9e8>
is_ajax: False
views.py
def index(request):
print(request.path) # 请求路径
print(request.method) # 请求方法
print(request.encoding) # 编码格式
# return HttpResponse('1111')
return render(request, 'blog/get_post_test.html') def get_text(request):
# if request.method == 'GET':
# return render(request, 'blog/get_post_test.html')
# elif request.method == 'POST':
a = request.GET.get('a')
b = request.GET.get('b')
print(a, b)
return HttpResponse('xxxxxxxx') def post_text(request):
if request.method == 'GET':
return render(request, 'blog/get_post_test.html')
elif request.method == 'POST':
a = request.POST.getlist('a') # getlist 一键多值
# a = request.POST.get('a')
# b = request.POST.get('b')
# print(a, b)
print(a)
return HttpResponse('xxxxxxxx')
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{#<form action="" method="get">#}
{% csrf_token %} {# 防止跨域请求 #}
<input type="text" name="a" id="a">
<input type="text" name="a" id="b">
<input type="submit" value="提交" id="c"> </form>
</body>
</html>
类视图
views.py
from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from .models import BlogModle2
from django.views import View
# Create your views here. class BlogIndex(View):
def get(self, request):
return render(request, 'blog/demo_index.html') class BlogAdd(View):
def get(self, request):
return render(request, 'blog/demo_add.html') def post(self, request):
title = request.POST.get('title')
content = request.POST.get('content')
blog = BlogModle2(title=title, content=content)
blog.save()
return render(request, 'blog/demo_add.html') class BlogList(View):
def get(self, request):
blog_list = BlogModle2.objects.all()
return render(request, 'blog/demo_list.html', context={'blog_list': blog_list}) class BlogDetail(View):
def get(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
return render(request, 'blog/demo_detail.html', context={'blog': blog}) class BlogDelete(View):
def get(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
if blog:
blog.delete()
return redirect(reverse('blog_list'))
else:
return HttpResponse('不存在这条博客') class BlogEdit(View): def get(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
return render(request, 'blog/demo_add.html', context={'blog': blog}) def post(self, request, blog_id):
blog = BlogModle2.objects.get(id=blog_id)
blog.title = request.POST.get('title')
blog.content = request.POST.get('content')
blog.save()
return redirect(reverse('blog_list'))
urls.py
path('index/', views.BlogIndex.as_view(), name='blog_index'),
path('add/', views.BlogAdd.as_view(), name='blog_add'),
path('list/', views.BlogList.as_view(), name='blog_list'),
path('detail/<blog_id>', views.BlogDetail.as_view(), name='blog_detail'),
path('delete/<blog_id>', views.BlogDelete.as_view(), name='blog_delete'),
path('edit/<blog_id>', views.BlogEdit.as_view(), name='blog_edit'),
文件上传
先在settings.py设置路径
创建文件夹
编写views.py
import os
from mysite.settings import MEDIA_ROOT class Upload_file(View):
def get(self, request):
return render(request, 'blog/file.html') def post(self, request):
# f1 = request.FILES['file']
f1 = request.FILES.get('file')
f1_name = os.path.join(MEDIA_ROOT, f1.name)
with open(f1_name, 'wb') as f:
for i in f1.chunks():
f.write(i)
return HttpResponse('上传成功')
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file">
<input type="submit">
</form>
</body>
</html>
HttpResponse对象
属性
def index(request):
response = HttpResponse('')
print(response.content)
print(response.status_code)
print(response.charset) return response
方法
设置cookie
# 设置cookie
import datetime
def set_cookie(request):
response = HttpResponse('设置cookie')
response.write('我是写入进去的')
# response.set_cookie('name', 'ing', max_age=100) # 设置多少秒之后过期
response.set_cookie('name', 'ing', expires=datetime.datetime(2019, 9, 6)) # 设置过期日期 return response def get_cookie(request):
cookie = request.COOKIES
print(cookie.get('name'))
return HttpResponse('获取cookie') def delete_cookie(request):
rs = HttpResponse("删除cookie")
rs.delete_cookie('name')
return rs
返回json数据
登录案例,设置session,需要先执行makemigrations, migrate
def home(request): # 主页
a = 1
# b = a + '1'
print('只是我视图函数在调用')
username = request.session.get('username', '未登录')
return render(request, 'form_test/home.html', context={'username': username}) class LoginTest(View): # 登录
def get(self, request):
return render(request, 'form_test/login.html') def post(self, request):
username = request.POST.get('username')
request.session['username'] = username # 字典传值, 会存到数据库
request.session.set_expiry(None) # 设置过期时间, 默认两周
print(request.session)
return redirect(reverse('home')) def login_out(request): # 登出
request.session.flush() # 清除会话数据
return redirect(reverse('home'))
settings中设置
# 是否关闭浏览器使得session过期,默认False
# SESSION_EXPIRE_AT_BROWSER_CLOSE = False
# 是否每次请求都保存session,默认修改之后保存
# SESSION_SAVE_EVERY_REQUEST = False
# session的cookie失效日期,默认两周
# SESSION_COOKIE_AGE = 1209600
创建models.py模型
from django.db import models # Create your models here.
class UserModel(models.Model):
username = models.CharField(max_length=30, unique=True)
password = models.CharField(max_length=100)
email = models.EmailField()
django form表单的使用,登录注册案例
views.py
from .models import UserModel
from .forms import RegisterForm, LoginForm class Register(View):
def get(self, request):
form = RegisterForm() # 实例化一个表单实例
return render(request, 'form_test/register.html', context={'form': form}) def post(self, request):
form = RegisterForm(request.POST) # 获取form表单的数据
if form.is_valid(): # 验证数据是否合法
username = form.cleaned_data.get('username') # 拿数据
password = form.cleaned_data.get('password')
password_repeat = form.cleaned_data.get('password_repeat')
email = form.cleaned_data.get('email')
if password == password_repeat:
UserModel.objects.create(username=username, password=password, email=email)
return HttpResponse('注册成功')
else:
return HttpResponse('注册失败') else:
return HttpResponse('两次密码不一致') class Login(View):
def get(self, request):
form =LoginForm() # 先获得表单实例
return render(request, 'form_test/login.html', context={'form': form}) def post(self, request):
form = LoginForm(request.POST) # 获取发送的请求值
if form.is_valid(): # 检测数据是否合法
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = UserModel.objects.filter(username=username, password=password)
if user:
request.session['username'] = username
return redirect(reverse('home'))
else:
return redirect(reverse('register'))
else:
return HttpResponse('登录失败')
forms.py
from django import forms # 可以验证也可以生成前端代码
class RegisterForm(forms.Form): # 注册表单
username = forms.CharField(max_length=30, min_length=6)
password = forms.CharField(max_length=30, min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
password_repeat = forms.CharField(max_length=30, min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
email = forms.EmailField() class LoginForm(forms.Form): # 登录表单
username = forms.CharField(max_length=30, min_length=6,
widget=forms.TextInput(attrs={'placeholder': '请输入用户名'}))
password = forms.CharField(max_length=30, min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': '请输入密码'}))
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
{# <input type="text" name="username">#}
<input type="submit" value="登录"> </form>
</body>
</html> <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="注册">
</form>
{{ username }}
</body>
</html>