Django {% url %} reverse not working

流过昼夜 提交于 2019-12-25 18:28:45

问题


I have a view in a Django 1.4 project:

def index(request):
    print reverse('menus_index')
    latest_menu_list = Menu.objects.all().order_by('name')
    return render_to_response('menus/index.html', {'latest_menu_list': latest_menu_list})

This works as expected and prints out the reversed URL which is /menus/.

Inside of the index.html template (which is called by this view) I have:

{% url menus_index %}

Which causes a NoReverseMatch at /menus/ error. Reverse for '' with arguments '()' and keyword arguments '{}' not found.

My application's urls.py is:

urlpatterns = patterns('menus.views',
url(r'^$','index', name='menus_index'),
url(r'^(?P<menu_id>\d+)/$','detail', name='menus_detail'),
)

Which is included in my project's urls.py file.

What am I doing wrong?

Update:

Here is the full index.html template code:

{% extends "base.html" %}
{% load url from future %}

{% block title %}
Menu Index
{% endblock %}

{% block content %}
{% if latest_menu_list %}
<ul>
    {% for menu in latest_menu_list %}
    <li><a href="{% url menus_index %}/{{ menu.id }}/">{{ menu.name }}</a></li>
    {% endfor %}
</ul>
{% else %}
   <p>No menus are available.</p>
{% endif %}
{% endblock %}

回答1:


Answer: use {% url 'menus_index' %}. That {% load url from future %} makes the quotes a requirement per https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#url




回答2:


Maybe this not menus_index? Paste full template code this.




回答3:


You should use add variable for reverse, somethink like this: {% url "menus_index" menu.slug %}



来源:https://stackoverflow.com/questions/10039050/django-url-reverse-not-working

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