Django GET method to pass parameters

Insert picture description here

Browser

URL format:

xxx? Parameter name 1=value 1¶meter name 2=value 2...

1. html hyperlink

<a href="/mypage?a=999&b=999">进入mypage</a>

Generate URL

127.0.0.1:8000/mypage/?a=100&b=200

2. html from form

<form action="/mypage" method="get">
        <input type="text" name="a">
        <input type="text" name="b">
        <input type="submit" value="提交">
</form>

Input value:
Insert picture description here
Generate URL

127.0.0.1:8000/mypage?a=10&b=100

3. Manual input

URL

127.0.0.1:8000/sum?start=1&stop=101&step=1

URL

    re_path(r'^mypage', views.mypage_view),
    re_path(r'^sum', views.sum_view),

view

def mypage_view(req):
    # http://127.0.0.1:8000/mypage/?a=100&b=200
    """此视图函数用来示意得到GET请求中的查询"""
    if req.method == "GET":
        # a = req.GET.get('a', "没有对应的值")
        a = req.GET.getlist('a')  # ['100']
        s = "a=" + str(a)
        # s = str(dict(req.GET)) 可以获得列表
        b = req.GET.getlist('b')  # ['200', '400']
        s += "   b=" + str(b)
        html = "<h1>结果===>%s <h1>" % s
        return HttpResponse(html)
    else:
        return HttpResponse("<h1>当前不是GET请求<h1>")
def sum_view(req):
    if req.method == "GET":
        start = req.GET.get('start', '1')
        stop = req.GET.get('stop', '101')
        step = req.GET.get('step', '1')
        sum = 0
        try:
            start = int(start)
            stop = int(stop)
            step = int(step)

            for i in range(start, stop, step):
                sum += i

            html = "<h1>结果===>%d <h1>" % sum
        except:
            html = "<h1>结果===>0 <h1>"

        return HttpResponse(html)
    else:
        return HttpResponse("<h1>当前不是GET请求<h1>")

Guess you like

Origin blog.csdn.net/weixin_45875105/article/details/111624420