django Removing hardcoded URLs in templates

2019-08-05 02:12发布

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条回答
来,给爷笑一个
2楼-- · 2019-08-05 03:01

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 %}
查看更多
登录 后发表回答