https://htmx.org logo
Join Discord
Powered by
# πŸ”₯-django-htmx
  • r

    red-france-69804

    08/05/2022, 10:39 AM
    FYI, this works as intented:
    Copy code
    python
    class DeleteListView(SingleObjectMixin, ListView):
    
        def delete(self, request, *args, **kwargs):
            """Add delete logic (without redirection) to ListView get method"""
            self.object = self.get_object()
            self.object.delete()
            return super().get(self, request, *args, **kwargs)
  • r

    red-france-69804

    08/05/2022, 10:43 AM
    Sorry I just noticed your message. That's a very interesting idea too, using event communication rather than custom Django views.
  • j

    jolly-kite-167

    08/06/2022, 1:46 AM
    my new server - https://discord.gg/family-main
  • i

    incalculable-holiday-29658

    08/06/2022, 7:24 AM
    how do you pass HX-Trigger on HttpResponseRedirect ?
  • b

    blue-ghost-19146

    08/06/2022, 7:46 AM
    Take a look at this: https://stackoverflow.com/questions/69538244/htmxaftersettle-not-working-with-hx-trigger
  • b

    blue-ghost-19146

    08/06/2022, 7:53 AM
    We use CBVs too, but I guess it depends how you implement them. We don’t explicitly use
    DeleteView
    etc, but instead have
    get
    ,
    put
    ,
    delete
    methods within one class. I definitely prefer Method 2 for simplicity, but I do agree that method 1 may have better atomicity. What do you mean by β€œhaving to deal with the UI between 2 requests” for method 2? I understand that there are 2 requests, the delete then the subsequent list update, but what challenges does that pose to the UI in between? It should be as simple as the delete view deleting the item from the DB, then the list view updating the list with the latest data, right?
  • r

    red-france-69804

    08/07/2022, 3:53 PM
    i ended up using your method, as it's very challenging to modify existing Django CBVs to make them do exactly what I want. The (simplified) code looks like this:
    Copy code
    python
    class RefreshTableMixin:
        """Fire an HX-Trigger event to be handled client side, to indicate that a table need to be refreshed.
        """
    
        def build_response(self, request, *args, **kwargs):
            response = super().build_response(self, request, *args, **kwargs)
            trigger_client_event(response, name=REFRESH_TABLE_EVENT, params=None)
            return response
    
    
    class EmptyResponse:
        def build_response(self, request, *args, **kwargs):
            return HttpResponse("")
    
    
    class HTMXDeleteView(RefreshTableMixin, EmptyResponse, DeleteView):
        """Delete View with empty response and no redirection
        Add a custom event to be used client-side with HTMX.
        """
    
        def delete(self, request, *args, **kwargs):
            self.object = self.get_object()
            self.object.delete()
            response = self.build_response(request)
    
            return response
  • r

    red-france-69804

    08/07/2022, 3:58 PM
    About your question, for example in my case, when I'm deleting an object, I need to manually hide the modal, otherwise the user will be able to click on "DELETE" a second time while the object is actually already delete. It's not awful but is just more work to handle. With hyperscript :
    Copy code
    html
            <button
              ...
              _="on refreshTableEvent remove .modal-open from #{@data-modal-content}"
              data-modal-content="modal-delete-{{record.pk}}-content"
            >
              Delete
            </button>
  • b

    bitter-monkey-50309

    08/07/2022, 5:21 PM
    May be worth considering putting the modal close on a trigger event, too. If the user gets an error (server crashes or their connection fails) then the modal disappears and there's no indication it's not worked. In one of my projects where I'm doing similar I've made mine return 3 triggers for refreshing content, closing modal and displaying a confirmation toast. Then I've got an
    onclick
    event on the button in the modal to disable it and then event handlers for HTMX errors to display a toast with a generic failure message and re-enable the button for the user to try again.
  • r

    red-france-69804

    08/07/2022, 9:34 PM
    Hi guys. I built a toast message system with htmx, hyperscript, and tailwind. I share the code here as it could help others. Feel free if you have any question or suggestion. It consists on two parts: - A View mixin to be used in CBVs, to embed HX-Trigger header containing the toast(s) data. - A template to built toasts
    <div>
    in the DOM, as the events are received.
  • r

    red-france-69804

    08/07/2022, 9:34 PM
    views.py
    Copy code
    python
    import secrets
    from django_htmx.http import trigger_client_event
    
    class MessageMixin:
        """Provide a way to add a formatable message (like toast) to a class based view, using attributes. Kwargs can be added to format message with dynamic data.
        An HX-Trigger event is fired to be handled client-side.
        """
    
        message: str | None = None
        message_level: str | None = None
        message_kwargs: dict = {}
    
        def build_response(self, request, *args, **kwargs):
            response = super().build_response(self, request, *args, **kwargs)
    
            trigger_client_event(
                response,
                name="showMessage",
                params=dict(
                    level=self.message_level,
                    message=self.message.format(**self.message_kwargs),
                    randomId=secrets.token_urlsafe(nbytes=5),  # allow to handle multiple toasts concurrenly
                ),
            )
    
            return response
    toaster.html
    Copy code
    html
    {# Toast template used to create actual toasts with render hyperscript method #}
    <template id="toast-template">
      <div
        id="toast-${randomId}"
        class="alert alert-${level} shadow-lg mb-3"
        _="init
          wait 2s
          transition my opacity to 0
          remove me"
      >
    
        <span>${message}</span>
        <button
          _="on click remove #toast-${randomId}"
          class="btn btn-xs btn-circle">
          βœ•
        </button>
      </template>
    
      {# Toaster (toasts wrapper) #}
      <div
        class="z-20 fixed bottom-4 right-8 ml-8"
        _="on showMessage(message,level,randomId) from body
          render #toast-template with (message: message, level: level, randomId: randomId)
          then put it at the end of me"
      >
      </div>
  • r

    red-france-69804

    08/07/2022, 9:37 PM
    Result :

    https://im5.ezgif.com/tmp/ezgif-5-137cb37675.gifβ–Ύ

  • w

    white-motorcycle-95262

    08/10/2022, 4:20 PM
    Can someone help me remember the difference between Django's HttpResponseRedirect and the HttpResponseClientRedirect from the django-htmx lib? Is it that the ClientRedirect forces a full refresh to the provided url and using HttpResponseRedirect would still implement e.g., the
    hx-target
    of the request?
  • r

    red-france-69804

    08/11/2022, 12:04 PM
    Based on the source code and the doc here : https://django-htmx.readthedocs.io/en/latest/http.html#django_htmx.http.HttpResponseClientRedirect It seems it's just a way to transform the "natural" response location, to a
    HX-Redirect
    attribute, to trigger the redirection from the client, using HTMX. I can't help more as I have no example usage in mind right now.
    Copy code
    python
    class HttpResponseClientRedirect(HttpResponseRedirectBase):
        status_code = 200
    
        def __init__(self, redirect_to: str, *args: Any, **kwargs: Any) -> None:
            super().__init__(redirect_to, *args, **kwargs)
            self["HX-Redirect"] = self["Location"]
            del self["Location"]
  • r

    red-france-69804

    08/11/2022, 3:03 PM
    Hi folks. I'm trying to implement the [active search pattern](https://htmx.org/examples/active-search/) example from HTMX in my Django project, and need some help. The HTML code looks like this:
    Copy code
    django
    <input
      id="search-field"
      type="search"
      name="search" {# this creates the 'search' GET query paramater #}
      hx-get="{% querystring %}" {# current URL with existing query parameters - search param will be added automatically #} 
      hx-trigger="keyup changed delay:500ms, search"
      hx-target="#table-container"
      hx-swap="outerHTML"
      hx-push-url="true"
    >
    The
    querystring
    template tag you see comes from django-tables (https://github.com/jieter/django-tables2/blob/master/django_tables2/templatetags/django_tables2.py) and as explained in the source code, it allows to build a relative url, keeping already existing query parameters. This is exactly what I need when running a search, as I want to keep other query parameters (like sorting). I'll describe my issue with an example:
 If I go directly to "http://localhost:8000/objects?sort=title", I can see that the value of hx-get is
    hx-get="?sort=title"
    , as expected. Which means if I run a search, the final search url suffix will be something like
    ?sort=title&search=foo
    (as expected). 

 However, if I go to http://localhost:8000/objects and then use a button on my UI to trigger an HTMX query that updates the URL to "http://localhost:8000/objects?sort=title", the value of hx-get is still empty (
    hx-get="?"
    ).
 Then, of course if I run a search, the final search url suffix misses the sorting. 

 All of this is obvious because the
    <input>
    part is NEVER updated by htmx. Hence the
    {% querystring %}
    tag has is evaluated once when loading the
    http://localhost:8000/objects
    page, and can't change after that. While I understand where my problem comes from, I'm not sure how to deal with this properly. Maybe include the
    <input>
    into the HTMX response (but feel unnatural)? Thanks for your help.
  • d

    delightful-student-39557

    08/15/2022, 8:33 AM
    Browser back button causes naked partial view in Django? Has anyone come across this before? I already have ig statement in my view to check if it’s htmx request or normal request. This works when I load the pages separately but browser back button still renders naked partial view.
  • c

    calm-queen-64495

    08/15/2022, 1:21 PM
    Evening, I am trying to do a simple hx-get to render a table using a ClassBased View, update form is in a modal. When I POst the form data goes in just fine but I don't know how to trigger the HX-trigger in the Def Post() method of the Update and Create views. Anyone done this?
  • c

    calm-queen-64495

    08/15/2022, 1:23 PM
    Copy code
    class RoleUpdateView(UpdateView):
        model = Role
        form_class = RoleForm
        template_name = "partials/role-form.html"
    
        def post(self, request, pk):
            return super().post(request)
  • e

    early-camera-41285

    08/15/2022, 2:49 PM
    Do you mean you want to set the
    HX-Trigger
    header on the response object?
  • c

    calm-queen-64495

    08/16/2022, 12:26 AM
    Yeh
  • c

    calm-queen-64495

    08/16/2022, 6:37 AM
    How would that be written?
  • c

    calm-queen-64495

    08/16/2022, 6:38 AM
    Ideally Id do it for Create and Update views
  • c

    calm-queen-64495

    08/16/2022, 7:42 AM
    def post(self, request, pk): super().post(request) return HttpResponse(status = 204, headers={"HX-Trigger": "roleCreated"})
  • c

    calm-queen-64495

    08/16/2022, 7:48 AM
    This works
  • c

    calm-queen-64495

    08/16/2022, 7:48 AM
    HTMX triggers and loads the rows
  • e

    early-camera-41285

    08/16/2022, 11:56 AM
    You got it, that's how I would do it in a CBV. I use FBVs:
    Copy code
    python
    def my_view(request):
      response = HttpResponse(status=204)
      response['HX-Trigger'] = 'myCustomEvent'
      return response
    
    def html_response(request):
      response = render(request, 'my_templage.html', {'context': ''})
      response['HX-Trigger'] = 'myCustomEvent'
      return response
  • c

    calm-queen-64495

    08/17/2022, 3:58 AM
    Using the SweetAlert HTMX example on a form Im trying to use hx-post hx-trigger=confirmed on the form and on the submit button
    Copy code
    _="on click
                 call Swal.fire({title: 'Confirm', text:'Do you want to continue?'})
                 if result.isConfirmed trigger confirmed">
    But the Modal closes along with the sweetalert, so the confirmed is not fired. How would you stop the modal from closing, so the use can choose to confirm or deny the request?
  • m

    mysterious-toddler-20573

    08/17/2022, 4:07 PM
    that looks right
  • m

    mysterious-toddler-20573

    08/17/2022, 4:07 PM
    straight from here:
  • m

    mysterious-toddler-20573

    08/17/2022, 4:07 PM
    https://htmx.org/examples/confirm/
1...686970...100Latest