django删除模板中的硬编码URL [英] django Removing hardcoded URLs in templates

查看:153
本文介绍了django删除模板中的硬编码URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以在模板文件中包含此代码,该代码将返回链接列表

I know that in a template file I can include this code which will return a list of links

{% for q in all %}
    <ul>
        <li><a href={% url 'detail' q.id %}>{{ q.question_text }}</a></li>
    </ul>
{% endfor %}

现在django将搜索名称 detail 在我的应用目录的 urls.py 文件中,它将自动给出 q的值。 id 。但是,如果我的网址包含多个变量,该怎么办?所以在这里我只能给出一个参数,即 q.id 。但是,如果我想提出多个论点怎么办。
希望我很清楚

Now django will search for the name 'detail' in the urls.py file of my app directory and it will automatically give the value of q.id to that argument. But what if I have a url that contains more than 1 variable. So here I can only give one argument i.e, q.id. But what if I want to give more than one argument. Hope I am clear

推荐答案

好吧,您可以看到 urls.py 作为URL如何映射到视图函数(和基于类的视图)的声明。网址可以具有任意数量的参数。

Well you can see the urls.py as a declaration of how URLs map to view functions (and class-based views). A url can have an arbitrary number of parameters.

例如,如果我们具有以下网址:

If we have for example the following URL:

    url(r'^detail/(?P<year>(\d+))/(?P<name>(\w+))/$', views.detail),

我们可以将此网址视为某种虚函数,会采用以下参数:

We can see this url as some sort of virtual function that would take parameters like:

def some_url(year, name):
    # ...
    pass

因此我们可以使用未命名参数构建此URL:

So we can construct this URL with unnamed parameters:

{% url 'detail' 1981 q.name %}

或具有 named 参数:

{% url 'detail' name=q.name year=1981 %}

这篇关于django删除模板中的硬编码URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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