djangodjango-templatesdjango-viewsdjango-contrib

Referencing django.contrib.auth.login in Django templates


I am new to Django and am having difficulty with using django.contrib.auth.login.

My urls.py:

from django.conf.urls import patterns, include, url
from myapp import views
from django.contrib import auth

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^accounts/', include('accounts.urls')),
    url(r'^accounts/login/$', auth.login)
)

Now, when I am trying to use the url in the template

<a href="{% url 'accounts/login' %}?next={{request.path}}">Login</a>

I am getting NoReverseMatch error. What am I doing wrong? Thanks.

EDIT1: I was finally able to resolve NoReverseMatch error. Thanks. I still have a problem though. Here is my updated code:

urls.py:

from django.conf.urls import patterns, include, url

from myapp import views
from django.contrib.auth.views import login

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^accounts/', include('accounts.urls')),   
    url(r'^accounts/login/$', login)
)

my template index.html:

<a href="{% url 'django.contrib.auth.views.login' %}?next={{request.path}}">Login</a>

The issue: When I get the page and click on "Login" I get the following error:

DoesNotExist at /accounts/login/

So, it looks for the view in accounts/login/ and I do not have login view there, since django.contrib.auth.views.login is supposed to provide me with the view. How should I modify my urls.py? Or is there a different way to resolve it? Thanks.

EDIT 2:

my accounts/urls.py:

from django.conf.urls import patterns, url

from accounts import views

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

Solution

  • There are a few things wrong with this. Firstly, you're trying to call a non-view function in your urls. "auth.login" is the login function provided by the django auth app, but:

    "auth.views.login" is the view function you want to be calling, so:

    from django.contrib.auth.views import login
    
    ...
        url(r'^accounts/login/$', login),
    

    Whenever there's something wrong with one of your views, reverse will not work (I'll try to find the relevant piece of documentation on that).

    Secondly, you're trying to reverse a URL path. Reverse will take the name of a view, or a URL name and return the URL for that. If you change your URLs to point to the view (as I mentioned above), akshar's answer should be correct:

    {% url 'django.contrib.auth.views.login' %}