Im using Django with htmx. I have set up a url as follows in my urls.py file:
urlpatterns = [
path('@/<username>/my_orders/', views.myordersview, name="myorders"),
]
and the myordersview function something like this:
@login_required
def myordersview(request, username):
if request.htmx:
return render(#something)
else:
return render(#something else)
Now Im making a call to that url with htmx in my frame.html file:
<a
hx-target="#content"
hx-get="{% url 'myorders' user.username %}">
My Orders
</a>
The <a> tag should also be displayed when a user is not logged in and redirect the unauthenticated user to a login page. The problem is, if a user is not logged in, no variable is passed into the url template tag aka user.username=''
and Django spits out this error
Reverse for 'myorders' with arguments '('',)' not found.
I dont want to do this because its ugly:
<a
hx-target="#content"
hx-get="
{% if user.is_authenticated %}
{% url 'myorders' user.username %}
{% else %}
{% url 'login' %}
{% endif %}
">
My Orders
</a>
Is there a simple way to solve this without using a custom template tag?
You can use the following middleware:
https://www.caktusgroup.com/blog/2022/11/11/how-handle-django-login-redirects-htmx/
This will handle all redirections for you each time user is not logged in.