https://htmx.org logo
Join Discord
Powered by
# 🔥-django-htmx
  • f

    fancy-elephant-10660

    01/18/2023, 9:48 AM
    Got question about hx-push-url="true" I have list of articles that get replaced by "more articles" link. So if you click they load nice replacing the last bunch. I added hx-push-url so people can share links. This works as expected. You can share the link and it works. In my django code I check request.htmx and then load the partial template. But here is my problem: If I go to the details of the article and hit then the back button my django/wagtail code decides this is surly a htmx request and thus only loads the partial. def get_template(self, request, *args, **kwargs): if request.htmx: if request.GET.get("load") == "page_article": return "pages/story/index/_articles.html How can I make sure that the back button from detail to my Index page is not seen as request.htmx and thus the correct template is loaded?
  • a

    aloof-farmer-99917

    01/18/2023, 9:57 AM
    maybe this: https://django-htmx.readthedocs.io/en/latest/middleware.html#django_htmx.middleware.HtmxDetails.history_restore_request ?
  • m

    miniature-waiter-15357

    01/18/2023, 11:24 AM
    Hi all, glad to meet some django-htmx fans. I recently built a cli tool to start a django + htmx project with additional commands to download the latest versions of htmx and its extensions, which might be useful to some people here. https://github.com/Tobi-De/fuzzy-couscous If you take a look, feedback are greatly appreciated.
  • m

    miniature-waiter-15357

    01/18/2023, 11:33 AM
    Do some people here follow conventions or rules when using htmx with django? View names, templates, urls, etc. I know there is no consensus on this a this point rules, but this is just to get some ideas.
  • r

    rich-coat-84078

    01/18/2023, 1:34 PM
    Hello everyone, I don't know where this is but I wanted to ask because I'm having a problem. I have a form like below. if "Cancel Request" is clicked in the form, "deleteproduct" form element will be destroy. my problem here is that HTMX cannot work without (I hope not) a process like hx-post-get.... is there a solution for this? ```python {% csrf_token %} Are you sure you want to delete ""? Cancel Request Delete
  • l

    lemon-rainbow-71647

    01/18/2023, 8:14 PM
    I remember guettli shared some naming pattern. See here: https://github.com/guettli/django-htmx-fun#naming-pattern
  • r

    refined-waiter-90422

    01/18/2023, 8:16 PM
    Best resource I've seen thus far on patterns https://github.com/spookylukey/django-htmx-patterns
  • m

    miniature-waiter-15357

    01/18/2023, 8:35 PM
    Me too
  • jQuery and other JS libraries not executing on boosted pages
    b

    billions-easter-81130

    01/21/2023, 1:53 PM
    Hi all, I have a weird problem in my project which I can't seem to figure out. It's likely just something stupid - at least, that's what I'm hoping for. I have one page within my project which contains 1..n image galleries. I utilize JS libraries justifiedGallery, which needs jQuery, and lighGallery to render those galleries nicely. I include all JS libraries within my
    <head>
    . I do not use
    defer
    for htmx (1.8.5), jQuery, justifiedGallery or lightGallery. I try to only include libraries on an as-needed basis, so htmx is included on all pages, but jQuery, justifiedGallery and lightGallery are only included in my gallery page's
    <head>
    . To render the gallery, as per the libraries' documentations, I put the following code below my images:
    Copy code
    html
    <script type="module">
        $("#lightgallery_77877f03-bb81-4d96-8e0d-c87c52b6b622").justifiedGallery({
            rowHeight : 200,
        }).on('jg.complete', function () {
            lightGallery(document.getElementById('lightgallery_77877f03-bb81-4d96-8e0d-c87c52b6b622'), {
                selector: '.image-tile',
                plugins: [lgThumbnail],
                speed: 500,
                download: true,
                licenseKey: '0000-0000-000-0000',
            });
        });
    </script>
    When I visit my gallery page directly (i.e. copy and paste URL into browser and press enter), everything works as expected - even with an empty browser cache to start with. When I visit my gallery page via a boosted link instead, on my first visit with a fresh browser cache, the gallery is not rendered correctly: Neither justifiedGallery nor lightGallery work at all. I get the following error in my browser console:
    ReferenceError: Can't find variable: $
    in Safari or
    Uncaught ReferenceError: $ is not defined
    in Firefox. The stack trace below that error refers to htmx.js, starting with line 1735. That line reads
    parent.insertBefore(newScript, script);
    and is part of
    function evalScript(script)
    .
    h
    • 2
    • 9
  • m

    microscopic-winter-35952

    01/27/2023, 5:09 PM
    I need to filter my database while live updating it too. However, the current rendering doubles the form and resets the filter to show all the data. How can I filter my data and update it at the same time filters.py
    Copy code
    import django_filters
    from django_filters import DateFilter
    from .models import CheckingStatus, Participant
    from django.db.models import Q
    
    
    class ParticipantFilter(django_filters.FilterSet):
        class Meta:
            model = Participant
            fields = '__all__'
    views.py
    Copy code
    def display_view(request):
        myFilter = ParticipantFilter(request.GET, queryset=Participant.objects.all())
        data = myFilter.qs
        return render(request, 'display.html', {'data': data, 'myFilter': myFilter})
    HTML
    Copy code
    <body>
              <form method ="get">
                {{myFilter.form}}
                <button class "btn btn-primary" type = "Submit"></button>
            </form>
            <br><br>
    
        <div id="table-results" hx-get="/display" hx-trigger="every 2s">
    
         <table border="1" class="table table-dark table-hover">
             <thead>
                 <th>First_name</th>
                 <th>Last_name</th>
                 <th>Age</th>
                 <th>Checking Status</th>
                 <th>Time</th>
                 <th>Date</th>
             </thead>
             {% for k in data  %}
             <tr>
                 <td>{{k.first_name}}</td>
                 <td>{{k.last_name}}</td>
                 <td>{{k.age}}</td>
                 <td>{{k.checking.checking_status}}</td>
                 <td>{{k.checking.time}}</td>
                 <td>{{k.checking.date}}</td>
             
             </tr>
             
             {% endfor %}
         </table>
        </div>
      </body>
    Thanks for your time
  • r

    rich-coat-84078

    01/30/2023, 12:45 PM
    Are there any big projects using htmx or is it only for small projects?
  • p

    purple-exabyte-65527

    01/30/2023, 8:28 PM
    Hello, if you want to include get parameters from your form, you need to add hx-include attribute to your "table-results" div. Also you probably don't want to rerender every 2s your form, so you can create a new template with your table only and modify your view. You have doubled form because you substitute your div with entire page
  • m

    miniature-lizard-24702

    01/31/2023, 10:32 PM
    If by project you include application/product then contexte uses it on their front end along with stimulus https://www.contexte.com/
  • m

    miniature-lizard-24702

    01/31/2023, 10:34 PM
    @melodic-advantage-28381 presented a talk about it: https://m.youtube.com/watch?v=3GObi93tjZI
  • c

    crooked-winter-42525

    02/02/2023, 8:26 PM
    daily reminder of how effective of a programmer you can be with django and htmx. These two technologies fit so well together.
  • m

    magnificent-camera-86904

    02/03/2023, 7:15 PM
    Hi all! New to the server = ) I added infinite scrolling to my Django Blog using HTMX. I also just added a GPT integration using HTMX where I click a button and it generates a website title, slug, and metadescription based on the contents of my blog post! I really love HTMX 🥰
  • l

    little-plumber-64748

    02/05/2023, 7:41 PM
    Hi all: Need some help with checkbox validation. How to check if the checkbox is checked before submitting the form using htmx.
  • b

    billions-architect-49743

    02/10/2023, 10:26 AM
    Hey, does anyone know of any alternatives for 'django-render-block' (https://github.com/clokep/django-render-block/) (for template fragments for django) that works for nested blocks? i.e
    Copy code
    {% block content %} <- Works targeting this
       {% block fragment %} <- Can't target this without hitting an error
       {% endblock fragment %}
    {% endblock content %}
  • b

    bitter-monkey-50309

    02/10/2023, 5:48 PM
    Not 100% sure what you mean by target, but I've used slippers and it's really nice https://github.com/mixxorz/slippers
  • b

    brief-cartoon-61118

    02/10/2023, 9:57 PM
    Hello everyone I am facing an issue with HTMX implementation with Django forms. I have implemented the HMTX in crispy form for user registration and it redirects me to the login form however, when I submit the login form it again takes me to the registration form again though the response from Django is to redirect the user to home page. My implementation to login form submit buttion is this:
  • b

    brief-cartoon-61118

    02/10/2023, 9:57 PM
    Copy code
    <button hx-swap="outerHTML" hx-target="login_form" type="submit" value="Submit" </button>
  • b

    brief-cartoon-61118

    02/10/2023, 10:01 PM
    My implementation in the Modelform for user registration is
    Copy code
    self.helper.attrs = {
                # Redirecting on the save to signup page again
                "hx-post": reverse_lazy("signup"),
                # To replace/swap the form with the information returned by django
                "hx-target": "#signup-form",
                # Ajax swap to replace the outer HTML (Avoiding placing html inside the target - form inside form)
                "hx-swap": "innerHTML",
            }
  • b

    brief-cartoon-61118

    02/11/2023, 8:33 AM
    Fixed the issue thanks a lot everyone
  • m

    magnificent-camera-86904

    02/11/2023, 2:38 PM
    I am currently using this JavaScript code in my Django app to dynamically count the number of characters in an input box. Could I do it in HTMX instead?
    Copy code
    js
    function countCharacters() {
        function count(input, count) {
          const charCount = count.querySelector(".char-count");
          charCount.textContent = input.value.length;
          input.addEventListener("input", () => {
            charCount.textContent = input.value.length;
          });
        }
      
        const titleInput = document.querySelector("#id_title");
        const titleCount = document.querySelector("#title-count");
        count(titleInput, titleCount);
      }
      
      window.onload = countCharacters;
    Given this Django template. The first element displays the number of characters in the
    value
    field of the second element.
    Copy code
    html
    <p class="card-text">
      <span class="text-success" id="title-count">Title Characters: <span class="char-count"></span></span>
    </p>
    
    <input type="text" name="title" value="I am a 25 character title" class="form-control" autofocus="" maxlength="250" required="" id="id_title">
    Ideally, I could see myself using something like
    hx-post
    to send the title to a view. Then the view would count the characters and send back a number. I would then use something like
    hx-swap
    to swap out the textContent of the
    char-count
    element. The only problem is that I don't know how I could make it so the element keeps updating with new content as the user types (basically listen to a keyUp event).
  • m

    magnificent-camera-86904

    02/12/2023, 4:55 AM
    Hey! I just implemented a character counter in HTMX and wanted to know what you guys thought of the way I implemented it. VIEW
    Copy code
    py
    def count_characters(request):
        title = request.POST["title"]
        character_count = len(title)
        return HttpResponse(character_count)
    TEMPLATE
    Copy code
    html
    <p class="card-text">
      <span class="text-success" id="title-count">Title Characters: <span class="char-count"></span></span>
    </p>
    
    <input autofocus="" class="form-control" hx-include="#id_title" hx-post="/count-characters/" hx-target=".char-count" hx-trigger="load, input" id="id_title" maxlength="250" name="title" required="" type="text" value="HELLO WORLD!">
  • m

    magnificent-camera-86904

    02/12/2023, 7:58 AM
    People are hating on it cause they think this should be client-side…but this is an admin-interface for me only and I personally don’t like putting extra JS imports or scripts into my Django apps. So there! I’m doing it server-side and no one can stop me.
  • e

    eager-psychiatrist-68229

    02/12/2023, 8:20 AM
    If it works, it works. Once performance becomes a concern, you’ll want to avoid an unnecessary round trip to the server because no data needs to be persisted here, and defer that kind of computation to the client.
  • e

    eager-psychiatrist-68229

    02/12/2023, 8:21 AM
    If you use serverless, this implementation will cost you real money
  • e

    eager-psychiatrist-68229

    02/12/2023, 8:22 AM
    Also, this can be done in a breeze with #796428329531605032
  • e

    eager-psychiatrist-68229

    02/12/2023, 8:23 AM
    Something like ‘on change put my.length into #length-container’s content’
1...899091...100Latest