Comments (7)
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?
from django-htmx.
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.
from django-htmx.
Some more food for thought: I just did a quick search in the htmx source, and it looks as if 3xx status codes are ignored.
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.
We are using @login_required in this case, a specialised version of that might be a solution. But I'm not sure if it is the right one.
from django-htmx.
I was thinking, would it be worth it to add this as a decorator? I think this use case extends beyond just login (although that's exactly what brought me here 😅) and could be applied selectively vs being run on all requests via middleware like so:
def htmx_redirect(func):
def wrapper(self, request, *args, **kwargs):
response = func(self, request, *args, **kwargs)
if request.htmx and isinstance(response, HttpResponseRedirect):
response['HX-Redirect'] = response['Location']
response.status_code = 204
return response
return wrapper
from django-htmx.
I also just discovered this issue, and this what I wrote -- I apply it as a decorator on HTMX-only views and it works quite well for my uses, though doesn't handle the I'm solving a different issue and can't delete my comment, so below is a general guard decorator for single views.HX-Redirect
header.
Click to expand!
def htmx_guard_redirect(redirect_name):
"""
Decorator for guarding HTMX-only function views.
If a request comes in to this endpoint that did not originate from HTMX,
respond with a redirect to the requested endpoint.
Usage:
@htmx_guard_redirect("homepage")
def htmx_only_function(request):
...
Takes an optional `test` boolean that bypasses the redirect.
"""
# https://stackoverflow.com/a/9030358
def _method_wrapper(view_method: Callable) -> Callable:
def _arguments_wrapper(
request: Request, *args, **kwargs
) -> HttpResponseRedirect | Callable:
testing = False
if "test" in kwargs.keys():
testing = kwargs.pop("test")
if not request.htmx and not testing:
return HttpResponseRedirect(reverse(redirect_name))
return view_method(request, *args, **kwargs)
return _arguments_wrapper
return _method_wrapper
from django-htmx.
This blog post highlights that returning a HTTP 303 status code might sometimes be particularly convenient with HTMX. Indeed, when you perform actions using HTTP methods like PUT / DELETE / PATCH and you want to redirect after the action is completed, using a 303 response ensures that the subsequent request after the redirection will be done using a GET method.
I'd just like to emphasize this point, which hasn't yet been mentioned, although it seems to be closely related to the potential new functionality being discussed here.
from django-htmx.
Personally, I'm in favour of having such a mechanism in django-htmx.
I've just started learning HTMX, having already worked with Django for several years, and I was surprised not to find a solution in the documentation for managing authenticated routes like in classic Django.
In addition, since it's a middleware, it lets the user choose whether or not to activate it depending on whether it can work for their project.
Finally, it would allow many Django components to work directly without having to override some methods that are sometimes not designed to be easily overridden, such as handle_no_permission
in LoginRequiredMixin for example.
In any case, thanks for the library, it works like a charm!
from django-htmx.
Related Issues (20)
- Load script via htmx and execute HOT 1
- variation on django_htmx_script - load error into target, instead of replacing whole page HOT 1
- HX-Reselect response header not implemeted HOT 1
- The middleware doesn't work properly in asgi mode HOT 2
- Support more than just "true" as value for boolean request headers HOT 2
- Template tag? HOT 1
- Redirect after login HOT 5
- example app doesn't run HOT 1
- Add support for hx-replace-url HOT 2
- hx-put, hx-delete HOT 1
- Detection of partial htmx request in the presence of hx-history HOT 8
- MyPy error with "show" argument to reswap: incompatible type "str" HOT 4
- Request: Add short description to the readme or documentation that explains why to use this package. HOT 2
- Multiple HX-Trigger Response Headers HOT 1
- Feature: Add a "render_htmx" function to eliminate boilerplate `if request.htmx: ...` in every view HOT 1
- Update page "context" without a full page reload
- Ignore this HOT 1
- trigger_client_event does not work with redirect HOT 3
- Extend HttpResponseLocation to Support select Attribute HOT 1
- 'select' kwarg support in HttpResponseLocation HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from django-htmx.