KristersP February 2016

Django 1.9.1 NoReverseMatch when using django.auth

I'm trying to learn django by following the book "Django by Example" and probably due to conflicting versions i'm running into this problem when trying to use django.auth together with some URL settings in settings.py. Im getting totally frustrated by now since i have no idea how to even begin debugging this error. Any help or advice would be much appreciated Here's the relevant part of the settings.py file

from django.core.urlresolvers import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_URL = reverse_lazy('logout')

app views.py:

from django.shortcuts import render, redirect
from django.shortcuts import HttpResponse
from django.contrib.auth import authenticate, login, logout
from .forms import LoginForm
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def dashboard(request):
    return render(request, 'account/dashboard.html', {'section': 'dashboard'})

urls.py

from django.conf.urls import url
from . import views

app_name = 'account'
urlpatterns = {
    url(r'^$', views.dashboard, name='dashboard'),
    url(r'^login/$', 'django.contrib.auth.views.login', name='login'),
    url(r'^logout/$', 'django.contrib.auth.views.logout', name='logout'),
    url(r'^logout-then-login/$', 'django.contrib.auth.views.logout_then_login', name='logout_then_login'),
}

Main urls.py :

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^account/', include('account.urls')),

]

Error Message

updated settings.py :

LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_URL = reverse_lazy('account:logout')

Answers


Håken Lid February 2016

When you use app_name that sets up a namespace that will be used when you include() that urls.py somewhere else.

So there's no url with the name "login", instead it's called "account:login", and that's the name you have to pass to reverse().

LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_URL = reverse_lazy('account:logout')

Relevant docs: URL namespaces and included URLconfs

If you are using django-extensions (you should), you can use the management command show_urls to get a nicely formatted list of all the url routes that are registered in your project.


KristersP February 2016

Big thanks to @ HÃ¥ken Lid

Two things needed a fix : 1. because of the app_name namespace in app/urls.py the URLs in settings.py were pointing to nowhere. code added 2. same goes for the base.html template , i had urls pointing to nowhere, needed to do the exact same thing as in the settings.py file ( add namespace)

Post Status

Asked in February 2016
Viewed 3,276 times
Voted 5
Answered 2 times

Search




Leave an answer