1
votes

I want to use reverse() in my Django view to avoid hard code, but get "Reverse for 'login' with arguments '()' and keyword arguments '{}' not found". Here is my code:

URLConf:

urlpatterns = patterns(
    '',
    url(r'^accounts/', include('accounts.urls', namespace="accounts")),
    url(r'^admin/', include(admin.site.urls)),
)

urls.py

urlpatterns = patterns(
    '',
    url(r'^login/$', views.login, name='login'),
    url(r'^signup/$', views.signup, name='signup'),
)

views.py:

def login(request):
    return render(request, reverse("login"))


def signup(request):
    return render(request, reverse("signup"))

Here is my traceback info:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/login/

Django Version: 1.7
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts')
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 "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 111. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/feizhao/dropbox/nahan/accounts/views.py" in login 11. return render(request, reverse("login")) File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/core/urlresolvers.py" in reverse 546. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/feizhao/.virtualenvs/nahan/lib/python2.7/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix 463. (lookup_view_s, args, kwargs, len(patterns), patterns))

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

I've seen some similar question in stackoverflow already, such as here, but no help.

Anyone can tell me why it's wrong? Thanks very much!

1

1 Answers

9
votes

You've given the urls a namespace so you need to include that in the name that you're reversing:

def login(request):
    return render(request, reverse("accounts:login"))


def signup(request):
    return render(request, reverse("accounts:signup"))