通过Django反向传递查询参数? [英] Pass a query parameter with django reverse?

查看:41
本文介绍了通过Django反向传递查询参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样访问的网址

I have a url that is meant to be accessed like

/people/raj/updates
/people/raj/updates?tag=food

但是Django反向URL解析器似乎没有做 tag = food 的规定,即将其检测为额外参数并放入查询字符串中.

But Django reverse URL resolver seems to have no provision to do tag=food, that is to detect it as an extra parameter and put in the query string.

如何传递查询参数?

推荐答案

这取决于您是在python代码中还是在模板中构建URL.

It depends on whether you are building the URL in the python code or in a template.

在python代码中(例如,视图):

In python code (e.g. the view):

from django.http import QueryDict

query_dictionary = QueryDict('', mutable=True)
query_dictionary.update(
    {
        'tag': 'food'
    }
)
url = '{base_url}?{querystring}'.format(
    base_url=reverse(my.url.name),
    querystring=query_dictionary.urlencode()
)

在模板中:

<a href="{% url 'my.url.name' %}?tag=food">My Link</a>

您还可以将QueryDict对象从视图传递到模板,并在模板中构建URL时使用该对象:

You caould also pass the QueryDict object from the view to the template and use that when building the URL in the template:

<a href="{% url 'my.url.name' %}?{{ query_dictionary.urlencode }}">My Link</a>

这篇关于通过Django反向传递查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆