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

我在谷歌上找了很多关于如何在模板中使用“ url”标签的答案,结果发现很多回复都说“你只需要将它插入到你的模板中,然后将它指向你想要的 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}),
)

我的‘ 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))

最后是 login _ view 所指向的 main.html:

<html>
<body>
test! <a href="{% url logout_view %}">logout</a>
</body>
</html>

那么为什么我每次都得到“无反向匹配”?

* (稍微有点不同的是,我不得不在所有渲染到响应的结尾使用‘ context _ instance = RequestContext (request)’,因为否则它不会在我的模板中识别{{ MEDIA _ URL }} ,我不能引用任何 css 或 js 文件。我不知道这是为什么。对我来说似乎并不正确) *

213437 次浏览

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 %}

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')

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)

I run into same problem.

What I found from documentation, we should use namedspace.

in your case {% url login:login_view %}

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>

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>