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:
- Modify your base template and hardcode the form (it is only a few
fields – don’t forget the CSRF token). - Use a context processor to make a Django form variable
available to every template. - 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.
- [Django]-Django Custom User Model Best Practice: User = get_user_model()?
- [Django]-Django-Debug-Toolbar is not showing
- [Django]-Django REST: What's the recommended approach for supporting nested collections in URLs, such as /users/5/snippets/
- [Django]-I am getting this error rest_framework.request.WrappedAttributeError
- [Django]-How to combine select_related() and value()?
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 %}
- [Django]-App specific default settings in Django?
- [Django]-I would like to add condition to Django DetailView