Django学习(二)

发布于:2024-07-27 ⋅ 阅读:(27) ⋅ 点赞:(0)

get请求

练习:

views.py

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

    path('test_method', views.test_method)

地址:

http://localhost:8000/test_method?a=1

响应:

POST请求:

 

 练习:

views.py

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

    path('test_method', views.test_method)

链接: http://localhost:8000/test_method?a=1

当我门直接访问时会出触发django的csrf检测

关闭csrf检测的方法

Post处理:


网站公告

今日签到

点亮在社区的每一天
去签到