收录日期:2021/02/27 02:05:35 时间:2009-03-14 04:53:17 标签:django,django-templates,django-urls

So, here is one of my urls.py

urlpatterns = patterns('items.views',
    url(r'^(?P<item_id>[\d+])/$', 'view_listing', name="item_view"),
)

And in my template, I can do this: <a href="{% url item_view 1 %}">here</a> and I'll get a link to the right page. Everything works great!

But, here is another one

urlpatterns = patterns('django.views.generic.list_detail',
    (r'^(?P<slug>[\w-]+)/$', 'object_detail', dict(page_info, slug_field='slug'), "page_view"),
)

But in my template if I try this: <a href="{% url page_view slug='TermsAndConditions' %}">Terms and Conditions</a> or this <a href="{% url page_view 'TermsAndConditions' %}">Terms and Conditions</a> it errors out with this error:

TemplateSyntaxError at /

Could not parse the remainder: ''TermsAndConditions '' from ''TermsAndConditions ''

Does anyone know if it's possible to use named urls with generic views and the url template tag like this? Or the right way to get it to work with generic views?

Thanks.

The solution is

<a href='{% url page_view slug="TermsAndConditions" %}'>Terms and Conditions</a>

The template system in Django only supports double quotes, which explains the syntax error you get when using single quotes. You will need to do

{% url page_view slug="TermsAndConditions" %}

If you omit the quotes, Django things you're referring to a variable named TermsAndConditions.

Don't put quotation marks around the string "TermsAndConditions":

{% url page_view slug=TermsAndConditions %}