我在google上寻找了很多有关如何在模板中使用'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}),
)
我的“登录”目录中的“ 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>
那么,为什么每次我都得到“ NoReverseMatch”?
*(略有不同的注解是我必须在所有响应响应的结尾处使用'context_instance = RequestContext(request)',因为否则,它将无法识别模板中的{{MEDIA_URL}},因此我无法引用任何CSS或JS文件。我不确定为什么会这样。对我来说似乎不正确)*
context_instance=RequestContext(request)
正确,这是允许模板访问提供给所有模板的上下文变量所必需的。默认情况下,这对于所有通用视图都是完成的,但是您需要在自定义视图中自己做。