question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Handle redirects when htmx == True

See original GitHub issue

In a project I’m working on we logout priviliged users after some time. This has the downside of returning a HttpResponseRedirect when issuing a htmx request, ie. when a user tries to use an already open browser tab the next day.

For now we have solved the problem by writing the following middleware:

class HtmxRedirectMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if request.htmx and isinstance(response, HttpResponseRedirect):
            # Set the HX-Redirect to the current location to imitate a reload
            response["HX-Redirect"] = response["Location"]
            # htmx only accepts 200's
            response.status_code = 200
        return response

This tells htmx to do a complete reload of the page leading to a redirect to the login page.

I think that the above approach might be a bit too generic - do we want to issue a redirect every time? For now it serves us fine since we are evaluating htmx in a small portion of our project.

The question is whether django-htmx should offer something similar?

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

6reactions
mfiscocommented, Mar 13, 2022

I’m also working on a project where the majority requests require authentication. For the time being we simply customized django’s LoginView

class AccountLoginView(LoginView):
    template_name = "accounts/login.html"

    def get(self, request, *args, **kwargs):
        """
        Triggers client-side redirect for htmx requests redirected to the login page.
        
        - Particularly useful when a user's session has expired but their client 
        is polling for a resource needing authentication. 

        """
        if request.htmx and REDIRECT_FIELD_NAME in request.GET:
            return HttpResponseClientRedirect(settings.LOGIN_URL)
        return super().get(request, *args, **kwargs)

Anyways, has there been any more ideas or thought given to adding this functionality to django-htmx?

1reaction
adamchainzcommented, Jul 8, 2021

I think that the above approach might be a bit too generic - do we want to issue a redirect every time?

This is my concern too. A server redirect isn’t necessarily a call for an HTMX redirect…

Ideally you’d instead update your “if not logged in then redirect” code to generate the correct response for htmx immediately, rather than modifying it after the fact. Of course that’s not always easy when you use e.g. django.contrib.auth.views.redirect_to_login.

I think we should let this one sit for a little, to think about it. I also hadn’t thought about not-logged-in requests so I will look at working with them in my project.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to implement a redirect with HTMX? - Stack Overflow
But from time to time I just need a real "phyiscal" redirect to another page. Any ideas how to achieve this without starting...
Read more >
How to Handle Django Login Redirects with HTMX
This post describes a Django middleware to help properly handle redirects when a session times out and the user attempts to POST to...
Read more >
Documentation - </> htmx
HX-Location - triggers a client-side redirect to a new location that acts as a swap; HX-Refresh - if set to "true" the client...
Read more >
With "follow redirect = true", 303 are followed #2806 - GitHub
Hello Describe the bug As you can see, the option is disabled And when a got a 303 and I'm on preview mode...
Read more >
(Optional) Configuring a webpage redirect
To add redirection rules for a bucket that already has static website hosting enabled, follow these steps. Open the Amazon S3 console at...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found