栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Django — HttpRequest对象、HttpResponse对象

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Django — HttpRequest对象、HttpResponse对象

对于HttpRequest对象这一知识点,在上篇完成的基础来进行说明。

1.HttpRequest对象

(1)GET属性

    创建test视图函数;

def test(request):
    if request.method == 'GET':
        print("method:",request.method)
        print("get:",request.GET)
        return render(request,'book/test.html')
    else:
        print("method:",request.method)
        print("post:",request.POST)
    print("path:",request.path)
    return HttpResponse("ok")

    创建test.html并且配置url;




    
    Title


        url(r"^test",test),

    效果如下: 

     

     

(2)POST属性

   以添加图书为例,首先创建一个create.tml模板文件;




    
    Title


书名:
页码:
出版日期:

    定义create视图函数并配置url; 

def create(request):
    if request.method == 'GET':
        # 渲染添加图书的表单页面
        return render(request,'book/create.html')
    else:
        bookinfo = BookInfo()
        bookinfo.bname = request.POST.get('bname')
        bookinfo.bpage = request.POST.get("bpage")
        bookinfo.bpub_date = request.POST.get('bpub_date')
        bookinfo.save()
        return HttpResponseRedirect("/book/index")
    url(r"^create",create),

     效果如下:

    

  注意:这里要注释掉settings.py文件中的MIDDLEWARE的crsf内容;

# 'django.middleware.csrf.CsrfViewMiddleware',
 2.HttpResponse对象

    以删除图书为例,首先创建一个delete视图;

from django.http import HttpResponseRedirect

def delete(request,bid):
    # 1.通过 bid 来查找 Book
    book = BookInfo.objects.get(id=bid)
    # 2.删除
    book.delete()
    # 3.重定向,让浏览器访问/index
    return HttpResponseRedirect("/book/index")

    直接配置路由;

    url(r"^delete/(d+)",delete),

    在原本创建的index.html模板中添加如下代码:




    
    图书信息


    添加 {% for book in books%}
  • {{book.bname}},{{book.bpage}}-- --{book.id}}">修改 {book.id}}">删除
  • {% endfor %}

    效果如下:(删除后)

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/665285.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号