Django学习(二)

get请求

练习:

views.py

python 复制代码
def test_method(request):
    if request.method == 'GET':
        print(request.GET)
        # 如果链接中没有参数a会报错
        print(request.GET['a'])
        # 使用这个方法,当查询不到参数时,不会报错而是返回你设置的值
        print(request.GET.get('c','no c'))
        # 当链接中传入多个a时,会返回列表;如果使用上面的两个方法时,只会返回最后一个值
        print(request.GET.getlist('a'))
    elif request.method == 'POST':
        pass
    return HttpResponse('ok')

urls.py

python 复制代码
    path('test_method', views.test_method)

地址:

http://localhost:8000/test_method?a=1

响应:

POST请求:

练习:

views.py

python 复制代码
FORM = """
<form action="/test_method" method="post">
用户名: <input type="text" name="name">
<input type="submit" value="提交">
</form>
 """


def test_method(request):
    if request.method == 'GET':
        print(request.GET)
        # 如果链接中没有参数a会报错
        print(request.GET['a'])
        # 使用这个方法,当查询不到参数时,不会报错而是返回你设置的值
        print(request.GET.get('c', 'no c'))
        # 当链接中传入多个a时,会返回列表;如果使用上面的两个方法时,只会返回最后一个值
        print(request.GET.getlist('a'))
        return HttpResponse(FORM)
    elif request.method == 'POST':
        print(request.POST['name'])
        return HttpResponse('post ok')
    return HttpResponse('ok')

urls.py

python 复制代码
    path('test_method', views.test_method)

链接: http://localhost:8000/test_method?a=1

当我门直接访问时会出触发django的csrf检测

关闭csrf检测的方法

Post处理:

相关推荐
Code额9 分钟前
ECMAScript 7~10 新特性
开发语言·javascript·ecmascript
tkt13 分钟前
Flutter 相关命令
前端
华科云商xiao徐13 分钟前
利用Ruby的Typhoeus编写爬虫程序
前端
和和和15 分钟前
前端优化都有啥
前端·面试
爱上大树的小猪15 分钟前
【前端基础】深入理解 JavaScript 展开运算符:数组合并与对象浅拷贝实战指南
前端·javascript·vue.js
普通且自信16 分钟前
领域模型 DSL 设计与实践
前端
林太白18 分钟前
学到了,强大的企业级NestJS必须了解一下
前端·后端·nestjs
qq_2602412318 分钟前
怎么检查网站CDN缓存是否生效
运维·前端·缓存
你的人类朋友19 分钟前
关于express中间件的工作原理
javascript·node.js·express
迷途小学生20 分钟前
迟到了几年的tailwind css初体验
前端·css