Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get {% url logout %} to work in my Django template?

My Django app's site-wide urls.py file looks like this:

urlpatterns = patterns('',
    url(r'^$', include('myApp.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url (
        r'^accounts/register/$', 
        RegistrationView.as_view(form_class=extendedRegistrationForm),
    ),  
    url(r'^accounts/', include('registration.backends.default.urls')),
    url(r'^', include('myApp.urls')),
)

I also have a urls.py specific to myApp but I have not shown that here because I don't think it's relevant.

In my template file, I have this:

{% url logout %}

It gives me this error:

'url' requires a non-empty first argument. The syntax changed in Django 1.5, see the docs.

When I change the template to:

{% url 'logout' %}

It gives me the following error:

Reverse for 'logout' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

How do I put a link to logout in my view?

like image 968
Saqib Ali Avatar asked Feb 13 '14 08:02

Saqib Ali


People also ask

What does form {% url %} do?

{% url 'contact-form' %} is a way to add a link to another one of your pages in the template. url tells the template to look in the URLs.py file. The thing in the quotes to the right, in this case contact-form , tells the template to look for something with name=contact-form .

How do I reference a URL in Django?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

What does the built in Django template tag URL do?

A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template.


2 Answers

Add a logout url like this:

url(r"^logout/$", "django.contrib.auth.views.logout_then_login",
    name="logout"),

The correct template syntax is:

{% url 'logout' %}
like image 135
arocks Avatar answered Sep 19 '22 14:09

arocks


You didn't include django.contrib.auth's URLs in your urls.py, so there is no logout URL.

Try adding something like

url(r'^auth/', include('django.contrib.auth.urls')),
like image 20
RemcoGerlich Avatar answered Sep 19 '22 14:09

RemcoGerlich