[Django]-How to make the login form available on whole site on Django

5👍

You can use an inclusion template tag to build a custom tag that looks like:

{% login_form %}

You might want to pass this tag the request.get_absolute_uri so that it can use it in a ?next={{ request.get_absolute_uri }} parameter to the login view so that the user can be redirected to the current page after login.

This way, you can put the login form anywhere you want in any template without violating the DRY principles. You can even embed it in your base template using something like:

{% if not user.is_authenticated %}
  {% login_form %}
{% else %}
  {# display welcome message. #}
{% endif %}

2👍

A couple of different ways you could do this:

  1. Modify your base template and hardcode the form (it is only a few
    fields – don’t forget the CSRF token).
  2. Use a context processor to make a Django form variable
    available to every template.
  3. Create a custom template tag to display
    the form and use it on your base template.

You’ll likely want to wrap the logic in the template like this:

{% if user.is_authenticated %}
   <!-- maybe show a logout link -->
{% else %}
   <!-- display your form using one of the methods above -->
{% endif %}

Note: if you are using the auth template context processor, the user variable will be available on all your templates.

1👍

I have embedded my login form within the base template, and pass request.user along to the templates of my site to display the login form only if the user is not already logged on.

So in my view dict I include 'user': request.user and my template looks similar to this:

{% if not user.is_authenticated %}
<form><fieldset><!-- Your login form here --></fieldset></form>
{% else %}
<!-- If you want to display something else if the user is logged in, like -->
<p>Welcome, {{ user }}!</p>
{% endif %}

Leave a comment