使用{%url ??? django模板中的%}

Sev*_*ths 70 django django-templates django-urls

我在google上看了很多关于如何在模板中使用'url'标签的答案,但却发现很多回复说'你只需将它插入模板并将其指向你想要的网址'.对我来说没有任何乐趣:(我已尽力尝试每一种排列,并在此作为最后手段使用.

所以这就是.我的urls.py看起来像这样:

from django.conf.urls.defaults import *
from login.views import *
from mainapp.views import *
import settings

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^weclaim/', include('weclaim.foo.urls')),
    (r'^login/', login_view),
    (r'^logout/', logout_view),
    ('^$', main_view),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    #(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': '/home/arthur/Software/django/weclaim/templates/static'}),
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}),
)
Run Code Online (Sandbox Code Playgroud)

我的'login'目录中的'views.py'如下所示:

from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib import auth

def login_view(request):
    if request.method == 'POST':
        uname = request.POST.get('username', '')
        psword = request.POST.get('password', '')
        user = auth.authenticate(username=uname, password=psword)
        # if the user logs in and is active
        if user is not None and user.is_active:
            auth.login(request, user)
            return render_to_response('main/main.html', {}, context_instance=RequestContext(request))
            #return redirect(main_view)
        else:
            return render_to_response('loginpage.html', {'box_width': '402', 'login_failed': '1',}, context_instance=RequestContext(request))
    else:
        return render_to_response('loginpage.html', {'box_width': '400',}, context_instance=RequestContext(request))

def logout_view(request):
    auth.logout(request)
    return render_to_response('loginpage.html', {'box_width': '402', 'logged_out': '1',}, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

最后是login_view点的main.html:

<html>
<body>
test! <a href="{% url logout_view %}">logout</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

那么为什么我每次都会得到'NoReverseMatch'呢?

*(稍微不同的说明我必须在所有渲染到响应的末尾使用'context_instance = RequestContext(request)',否则它将无法识别我的模板中的{{MEDIA_URL}}而我无法引用任何css或js文件.我不确定为什么会这样.对我来说似乎不对)*

Mik*_*e S 94

所选答案已过期,没有其他人为我工作(Django 1.6和[apparantly]没有注册名称空间.)

对于Django 1.5及更高版本(来自文档)

警告 不要忘记在函数路径或模式名称周围加上引号!

使用命名URL,您可以执行以下操作:

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

如果视图采用另一个参数也很容易

def login(request, extra_param):
...
<a href="{% url 'login' 'some_string_containing_relevant_data' %}">login</a>
Run Code Online (Sandbox Code Playgroud)

  • 应该选择这个作为答案.在较新的django版本中不推荐使用字符串进行反向匹配URL. (5认同)

Mar*_*row 48

logout_view您应该在urls.py文件中提供一个字符串,而不是导入该函数:

所以没有 (r'^login/', login_view),

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

这是做事的标准方式.然后,您可以使用以下方式访问模板中的URL:

{% url login.views.login_view %}
Run Code Online (Sandbox Code Playgroud)

  • 这不再是正确的答案 (4认同)
  • 仅仅因为我来自谷歌,我应该说,对于django 1.8+,传递字符串作为视图参数已被弃用,并将很快删除.你应该像在这篇文章中那样传递callable. (3认同)
  • 是的,绝对使用字符串.这样,您也可以使用前缀,而不必将所有视图函数导入URLConf. (2认同)

Bog*_*tyr 39

确保(django 1.5及更高版本)你将url名称放在引号中,如果你的url接受参数,它们应该在引号之外(我花了几个小时搞清楚这个错误!).

{% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
<a href="{{ the_url }}"> link_name </a>
Run Code Online (Sandbox Code Playgroud)

  • 使用正确的文档也有帮助,因为它们会不断更改语法:1.4中的{{url app_views.client client.id%}}(无引号),{%url'app_views.client'client.id%}”(在1.5 -1.7中使用引号),在1.8中使用“ {%url'app-views-client'client.id%}”(没有下划线或点,仅是破折号)。 (2认同)

Ber*_*ant 17

url模板标签将通过参数作为一个字符串,而不是作为一个函数引用reverse().最简单的方法是name在视图中添加一个:

url(r'^/logout/' , logout_view, name='logout_view')
Run Code Online (Sandbox Code Playgroud)


小智 12

我遇到了同样的问题.

我从文档中发现,我们应该使用namedspace.

在你的情况下 {% url login:login_view %}