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.

requires_HTMX decorator

See original GitHub issue

Description

I’ve implemented the following decorator and found it quite useful and just wanted to share.

The idea is to replicate the requires_http_methods variants like requires_POST, and redirect the user to a more relevant page if they (or their browser) somehow accidentally try to access a HTMX only endpoint. I’ve at least had some oddities of somehow getting there.

The decorator is pretty straight forward:

from functools import wraps

def requires_HTMX(redirect_url):
    def decorator(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            if not request.htmx:
                _redirect_url = (
                    redirect_url(request, *args, **kwargs)
                    if callable(redirect_url) else redirect_url
                )
                return redirect(_redirect_url)

            return func(request, *args, **kwargs)

        return inner

    return decorator

Basic usage:

@requires_HTMX(redirect_url=reverse("some-default-page"))
def htmx_only_view(request):
    return render(request, "my_awesome_htmx_template.html")

but can also be used to redirect the user to a page which is relevant to the view:


def _get_post_url(request, post_id):
    return reverse("post-detail", kwargs={"post_id": post_id})

@requires_HTMX(redirect_url=_get_post_url)
def render_post_form(request, post_id):
    ...
    return render(request, "post_form.html", context=context)

which is quite useful when dealing with many HTMX only views tied together.

If this makes sense and you could see it work in django-htmx, I would love to do a PR with tests and documentation @adamchainz - if it is out of scope for the project that is also fine 😃

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
adamchainzcommented, Mar 14, 2022

Oh but it was not non-directly-loadable URLs I was pushing. I had just guessing that hx-push-url might be the reason - I’m not sure if it was.

Please come back with more info then 😃

I think there’s a key difference with require_http_methods - for wrong methods, there isn’t anything sensible to return. But HTML fragments are sensible and very useful for debugging, scraping, etc.

0reactions
valbergcommented, Mar 14, 2022

Will do!

The decorator could configured to be disabled if DEBUG=True - also as an opt-in it is/would be just a safe-guard against wrong usage if one chooses to use it. Having it redirect could also be optional, making it more akin to require_http_methods.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Marton Trencseni – Python decorator patterns - Bytepawn
I show toy implementations of Python decorator patterns such as @measure, @repeat, @trace, @count, @singleton, and @app.route (made famous ...
Read more >
How to make a decorator - Python Morsels
A decorator is a function that accepts a function and returns a function. That's true for function decorators at least.
Read more >
Python Decorators II: Decorator Arguments - Artima
In part I, I showed how to use decorators without arguments, primarily using classes as decorators because I find them easier to think...
Read more >
7 Levels of Using Decorators in Python | by Yang Zhou - Medium
The decorator is just another functional programming feature in Python. It receives a callable (function, method or class), and returns a ...
Read more >
The Single Most Useful Decorator in Python - YouTube
The most useful decorator in Python is @cache.It's from the functools library (and a similar variant called @lru_cache too).
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