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处理:

相关推荐
灵感__idea2 小时前
JavaScript高级程序设计(第5版):好的编程就是掌控感
前端·javascript·程序员
烛阴3 小时前
Mix
前端·webgl
代码续发3 小时前
前端组件梳理
前端
东林牧之3 小时前
Django+celery异步:拿来即用,可移植性高
后端·python·django
试图让你心动4 小时前
原生input添加删除图标类似vue里面移入显示删除[jquery]
前端·vue.js·jquery
陈不知代码4 小时前
uniapp创建vue3+ts+pinia+sass项目
前端·uni-app·sass
小王码农记4 小时前
sass中@mixin与 @include
前端·sass
陈琦鹏4 小时前
轻松管理 WebSocket 连接!easy-websocket-client
前端·vue.js·websocket
hui函数5 小时前
掌握JavaScript函数封装与作用域
前端·javascript
行板Andante5 小时前
前端设计中如何在鼠标悬浮时同步修改块内样式
前端