Search code examples
djangodjango-formsdjango-admindjango-viewsdjango-login

Django Logout Button


This may seem like a silly question but I can't find anything to help. How would you create a logout button on every view like the one available in the admin page?


Solution

  • Use templates inheritance: https://docs.djangoproject.com/en/dev/topics/templates/#template-inheritance or include tag: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#include

    Example with template inheritance: We have a base template for all pages on our application:

    base.html

    <html>
    <head>...</head>
    <body>
        <a href="/logout">logout</a>  # or use the "url" tag: {% url logout_named_view %}
    
        {% block content %} {% endblock %}
    </body>
    </html>
    

    other_pages.html

    {% extends "base.html" %}
    {% block content %}
        <div class="content">....</div>
        ....
        ....
    {% endblock %}
    

    Now, we have a logout link on all pages inherited from the base.html

    Example with include tag:

    user_panel.html

    <div class="user_panel">
        <a href="/logout">logout</a>
    </div>
    

    other_pages

    <html>
    <head>...</head>
    <body>
        {% include "user_panel.html" %}
        ...
        ...
    </body>
    </html>
    

    I recommend for a solution to your problem using template inheritance