Using {% url ??? %} in django templates

后端 未结 6 2318
囚心锁ツ
囚心锁ツ 2020-12-07 13:02

I have looked a lot on google for answers of how to use the \'url\' tag in templates only to find many responses saying \'You just insert it into your template and point it

相关标签:
6条回答
  • 2020-12-07 13:38

    Judging from your example, shouldn't it be {% url myproject.login.views.login_view %} and end of story? (replace myproject with your actual project name)

    0 讨论(0)
  • 2020-12-07 13:40

    I run into same problem.

    What I found from documentation, we should use namedspace.

    in your case {% url login:login_view %}

    0 讨论(0)
  • 2020-12-07 13:41

    Instead of importing the logout_view function, you should provide a string in your urls.py file:

    So not (r'^login/', login_view),

    but (r'^login/', 'login.views.login_view'),

    That is the standard way of doing things. Then you can access the URL in your templates using:

    {% url login.views.login_view %}
    
    0 讨论(0)
  • 2020-12-07 13:48

    The selected answer is out of date and no others worked for me (Django 1.6 and [apparantly] no registered namespace.)

    For Django 1.5 and later (from the docs)

    Warning Don’t forget to put quotes around the function path or pattern name!

    With a named URL you could do:

    (r'^login/', login_view, name='login'),
    ...
    <a href="{% url 'login' %}">logout</a>
    

    Just as easy if the view takes another parameter

    def login(request, extra_param):
    ...
    <a href="{% url 'login' 'some_string_containing_relevant_data' %}">login</a>
    
    0 讨论(0)
  • 2020-12-07 13:48

    Make sure (django 1.5 and beyond) that you put the url name in quotes, and if your url takes parameters they should be outside of the quotes (I spent hours figuring out this mistake!).

    {% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
    <a href="{{ the_url }}"> link_name </a>
    
    0 讨论(0)
  • 2020-12-07 13:56

    The url template tag will pass the parameter as a string and not as a function reference to reverse(). The simplest way to get this working is adding a name to the view:

    url(r'^/logout/' , logout_view, name='logout_view')
    
    0 讨论(0)
提交回复
热议问题