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

相关推荐
yuanyxh14 分钟前
Mac 软件推荐
前端·javascript·程序员
万少19 分钟前
AtomCode开发微信小程序《谁去呀》 全流程
前端·javascript·后端
某人辛木33 分钟前
Web自动化测试
前端·python·pycharm·pytest
Kagol1 小时前
Superpowers GSD gstack AgentSkills深度测评
前端·人工智能
excel2 小时前
JavaScript 字符串与模板字面量:从表象到本质理解
前端
京东云开发者2 小时前
当AI成为导演-如何用AI创作动漫短剧
前端
李白的天不白3 小时前
使用 SmartAdmin 进行前后端开发
java·前端
乘风gg3 小时前
🤡PUA AI Coding 工具 的 10 条终极语录
前端·ai编程·claude
学Linux的语莫3 小时前
Vue 3 入门教程
前端·javascript·vue.js
怕浪猫4 小时前
第一章、Chrome DevTools Protocol (CDP) 详解
前端·javascript·chrome