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

相关推荐
Rsun045517 小时前
React相关面试题
前端·react.js·前端框架
Lao乾妈官方认证唯一女友:D7 小时前
通过plasmo的wallet扩展添加新钱包
javascript·web3·区块链
ALKAOUA7 小时前
力扣面试150题刷题分享
javascript·笔记
鹏多多.7 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter·ios·前端框架
LawrenceLan7 小时前
37.Flutter 零基础入门(三十七):SnackBar 与提示信息 —— 页面反馈与用户交互必学
开发语言·前端·flutter·dart
迪巴拉15258 小时前
基于Vue与Spring Boot+Open Cv的智慧校园考勤系统
前端·vue.js·spring boot
swipe8 小时前
JavaScript 对象与属性描述符:从原理到实战
前端·javascript·面试
&活在当下&8 小时前
Vue3 h函数用法详解
前端·javascript·vue.js