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

相关推荐
bubusa~>_<10 分钟前
解决npm install 出现error,比如:ERR_SSL_CIPHER_OPERATION_FAILED
前端·npm·node.js
yanglamei196223 分钟前
基于Python+Django+Vue的旅游景区推荐系统系统设计与实现源代码+数据库+使用说明
vue.js·python·django
[廾匸]35 分钟前
cesium视频投影
javascript·无人机·cesium·cesium.js·视频投影
流烟默1 小时前
vue和微信小程序处理markdown格式数据
前端·vue.js·微信小程序
梨落秋溪、1 小时前
输入框元素覆盖冲突
java·服务器·前端
菲力蒲LY1 小时前
vue 手写分页
前端·javascript·vue.js
一丢丢@zml2 小时前
new 一个构造函数的过程以及手写 new
javascript·手写new
天下皆白_唯我独黑2 小时前
npm 安装扩展遇到证书失效解决方案
前端·npm·node.js
~欸嘿2 小时前
Could not download npm for node v14.21.3(nvm无法下载节点v14.21.3的npm)
前端·npm·node.js
化作繁星3 小时前
React 高阶组件的优缺点
前端·javascript·react.js