django Removing hardcoded URLs in templates

岁酱吖の 提交于 2019-12-11 05:09:13

问题


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 %}

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


回答1:


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

So we can construct this URL with unnamed parameters:

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

or with named parameters:

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


来源:https://stackoverflow.com/questions/51123041/django-removing-hardcoded-urls-in-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!