Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly get url for the login view in template?

I have a small problem with figuring out how {% url 'something' %} works in django templates.

When I run my website in debug mode, I see this in stdout:

web_1 | [21/Dec/2015 11:29:45] "GET /accounts/profile HTTP/1.1" 302 0
web_1 | /usr/local/lib/python3.5/site-packages/django/template/defaulttags.py:499: RemovedInDjango110Warning: Reversing by dotted path is deprecated (django.contrib.auth.views.login).
web_1 |   url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
web_1 | 

The /accounts/profile maps to a template, and the only place in this template that mentions django.contrib.auth.views.login is the following:

<a href="{% url 'django.contrib.auth.views.logout' %}?next={% url 'django.contrib.auth.views.login' %}">Log out</a>

So, I guess that for some reason this is not the proper way to use {% url %} command. What is the proper way? How to get rid of this warning?

Here are my urlpatterns:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^accounts/', include('django.contrib.auth.urls')),
    url(r'^accounts/profile', views.profile_view),
    url(r'^$', RedirectView.as_view(url=reverse_lazy(views.profile_view)))
]
like image 907
CrabMan Avatar asked Dec 21 '15 11:12

CrabMan


2 Answers

You should use the name of the url, instead of its dotted path.

In this case, you have included the url patterns from django.contrib.auth.urls. If you look at that urls file, you can see that the name of the views are login and logout.

urlpatterns = [
    url(r'^login/$', views.login, name='login'),
    url(r'^logout/$', views.logout, name='logout'),
    ...
]

Therefore, change your link to:

<a href="{% url 'logout' %}?next={% url 'login' %}">Log out</a>
like image 112
Alasdair Avatar answered Sep 28 '22 14:09

Alasdair


Have a look at urls.py

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

you can refer the name when using url

{% url 'login' %}

and

{% url 'logout' %}

or if you need to logout with next then

<a href="{% url logout %}?next=/accounts/login/">Logout</a>

Check out this post 'django.contrib.auth.views.login'

like image 30
fragles Avatar answered Sep 28 '22 14:09

fragles