Django无法解析网址名称

时间:2014-11-11 14:37:23

标签: python django url django-views

我是Django的新手。

代码似乎无法解析我的"登录" url,我需要你的帮助继续我的发展。

以下是我得到的例外情况:

Environment:


Request Method: GET
Request URL: http://localhost:9999/bz/logout/

Django Version: 1.7
Python Version: 3.4.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bz')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "D:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\dev\python\eli\bz\views.py" in user_logout
  102.     return HttpResponseRedirect(reverse('login'), {'logged_out_success_message': user.username + " logged out successfully"})
File "D:\Python34\lib\site-packages\django\core\urlresolvers.py" in reverse
  546.     return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "D:\Python34\lib\site-packages\django\core\urlresolvers.py" in _reverse_with_prefix
  463.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /bz/logout/
Exception Value: Reverse for 'login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

这是我的urls.py:

from django.conf.urls import patterns, url

from bz import views

urlpatterns = patterns('',
  (r'^$', views.index),
  url(r'^login/$', views.user_login, name='login'),
  (r'^logout/$', views.user_logout),
  (r'^register/$', views.register),
  )

这是解决方案失败的问题部分:

def user_logout(request):
  user = request.user
  if user.is_authenticated:
    logout(request)
    return HttpResponseRedirect(reverse('login'), {'logged_out_success_message': user.username + " logged out successfully"})
  else:
    return render(request, 'bz/index.html', {})

我们将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:2)

好吧,伙计们,发现了问题。 当使用“反向”时,我忘了添加应用程序的名称。 所以以下就是诀窍。

而不是:

return HttpResponseRedirect(reverse('login'), {'logged_out_success_message': user.username + " logged out successfully"})

我写道(添加'bz:'作为前缀):

return HttpResponseRedirect(reverse('bz:login'), {'logged_out_success_message': user.username + " logged out successfully"})

现在它有效。 谢谢。