问题
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)))
]
回答1:
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>
回答2:
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'
回答3:
In urls.py add the name to each relevant entry (not the the ones which include other definitions, as the name would be ignored)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('django.contrib.auth.urls')),
url(r'^accounts/profile', views.profile_view, name='acc_profile'),
url(r'^$', RedirectView.as_view(url=reverse_lazy(views.profile_view)), name='home')
]
Then in the templates use the name of the url entry, as defined above i.e.
<a href="{% url 'optional_template_namespace:entry_name' %}">The link text</a>
In the given case, the login and logout urls come from the standard django.contrib.auth.urls and their name is simple enough (see here for further info)
<a href="{% url 'logout' %}?next={% url 'login' %}">Log out</a>
来源:https://stackoverflow.com/questions/34394900/how-to-properly-get-url-for-the-login-view-in-template