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

相关推荐
小白学习日记34 分钟前
【复习】HTML常用标签<table>
前端·html
john_hjy38 分钟前
11. 异步编程
运维·服务器·javascript
风清扬_jd1 小时前
Chromium 中JavaScript Fetch API接口c++代码实现(二)
javascript·c++·chrome
丁总学Java1 小时前
微信小程序-npm支持-如何使用npm包
前端·微信小程序·npm·node.js
yanlele1 小时前
前瞻 - 盘点 ES2025 已经定稿的语法规范
前端·javascript·代码规范
It'sMyGo1 小时前
Javascript数组研究09_Array.prototype[Symbol.unscopables]
开发语言·javascript·原型模式
懒羊羊大王呀1 小时前
CSS——属性值计算
前端·css
xgq2 小时前
使用File System Access API 直接读写本地文件
前端·javascript·面试
李是啥也不会2 小时前
数组的概念
javascript
用户3157476081352 小时前
前端之路-了解原型和原型链
前端