1

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?

pepsizero
  • 11
  • 3
  • You should definitely have different URL's. If you are still interested in optional URL parameters, then have a look here: https://stackoverflow.com/questions/2325433/making-a-regex-django-url-token-optional – Marco Mar 01 '23 at 14:31

1 Answers1

0

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.

mariodev
  • 13,928
  • 3
  • 49
  • 61