requires_HTMX decorator
See original GitHub issueDescription
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:
- Created 2 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
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.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
.