implement login URL as templatetag

this eases testing as it allows generating that URL inside a test
instead of scraping HTML output
This commit is contained in:
Valentin Gagarin 2025-02-19 15:40:51 +01:00
parent 647d89798e
commit fc586273dc
3 changed files with 19 additions and 2 deletions

View file

@ -16,10 +16,11 @@
<body> <body>
<header> <header>
{% load custom_tags %}
{% if user.is_authenticated %} {% if user.is_authenticated %}
<p>Welcome, {{ user.username }}! <a href="{% url 'logout' %}?next={{ request.path }}">Logout</a></p> <p>Welcome, {{ user.username }}! <a href="{% auth_url 'logout' %}">Logout</a></p>
{% else %} {% else %}
<p><a href="{% url 'login' %}?next={{ request.path }}">Login</a></p> <p><a href="{% auth_url 'login' %}">Login</a></p>
{% endif %} {% endif %}
</header> </header>
{% block navigation %} {% block navigation %}

View file

View file

@ -0,0 +1,16 @@
from django import template
from django.urls import reverse
from urllib.parse import urlencode
register = template.Library()
@register.simple_tag(takes_context=True)
def auth_url(context, action):
"""Generate login/logout URL with current path as redirect."""
request = context['request']
view = context.get('view')
redirect_field_name = getattr(view, 'redirect_field_name', 'next')
base_url = reverse(action)
query_params = {redirect_field_name: request.path}
return f"{base_url}?{urlencode(query_params)}"