Putting a django login form on every page

后端 未结 4 919
执念已碎
执念已碎 2020-11-27 11:35

I\'d like the login form (AuthenticationForm from django.contrib.auth) to appear on every page in my site if the user is not logged in. When the user logs in, they will be r

4条回答
  •  醉话见心
    2020-11-27 12:07

    The easiest way is probably to put the form in manually in a base template like so:

    {% if user.is_authenticated %}
        
    {% csrf_token %}
    {% else %} {# display something else here... #} {% endif %}

    and then just write a view hooked up to a URL named "login" to handle the form as you would normally (using a form object that matches the above form). Have the view redirect to request.META['HTTP_REFERER'] to show it on the same page as the one that submitted.

    This approach avoids middleware or the need to make a form available to every single template through the context.

    Update: There are some problems with this approach; need to think on it a little more. Hopefully it at least gets you going in the right direction.

提交回复
热议问题