@Tomk,这是一个示例,可以让您很好地了解如何使用@guettli 的解决方案。这是来自管理事件的项目的编辑片段。
视图.py
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.shortcuts import get_object_or_404
from .models import Event
class HTTPResponseHXRedirect(HttpResponseRedirect):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self["HX-Redirect"] = self["Location"]
status_code = 200
@login_required
def delete_event(request, event_id: int):
event = get_object_or_404(Event, pk=event_id)
if request.method == "DELETE":
event.delete()
messages.add_message(request, messages.SUCCESS, "Successfully deleted event!")
return HTTPResponseHXRedirect(redirect_to=reverse_lazy("events"))
网址.py
from django.urls import reverse_lazy
urlpatterns = [
path("events", views.list_events, name="events"),
path(
"events/delete/<int:event_id>", views.delete_event, name="delete_event"
)
]
编辑事件.html
...
<span hx-delete="{% url 'delete_event' event.id %}"
hx-confirm="Are you sure you want to delete this event?"
hx-swap="none"
class="btn btn-danger fa fa-trash">
</span>
...
使用这种方法将允许您使用 htmx,但也可以让 django 重定向前端。如果您要在没有 htmx 的情况下执行此操作,您通常会使用 djangoredirect
函数。