【问题标题】:Dynamically update table when creating new enty using HTMX使用 HTMX 创建新实体时动态更新表
【发布时间】:2021-03-16 22:34:38
【问题描述】:

recent success 之后,在一些简单的 HTMX 任务中,我想通过动态更新表格的模态字段扩展 adamchainz django-htmx example。我不确定我是否在render ... 中返回了正确的东西,但我的问题是,表格没有更新。只有当我点击重新加载时。

查看:

class CreateProductView(TemplateView):
    template_name = "app/product_create.html"
    form_class = OrderForm

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, {'form': self.form_class()})

    def post(self, request):
        Product.objects.create(name = request.POST["name"], price = request.POST["price"])
        part_template = "app/partial-rendering.html"
        return render(request, part_template, {"base_template": "app/_partial.html"})

urls.py:

path("create/", views.CreateProductView.as_view(), name = 'create'),

这是我的index.html,里面有表格:

<div class="..."><button class="btn btn-primary" 
                         id="showButton"
                         hx-get="/create" 
                         hx-target="#modal-create">create</button</div>

<main role="main" id="main">{% include "app/orders_table.html" %}</main>
<div id="modal-create"></div>

我也有一个partial-rendering.html

{% extends base_template %}

{% block main %}
     {% include "app/product_table.html" %}
{% endblock %}

还有一个_partial.html

<main id="main">
    {% block main %}{% endblock %}
</main>

我不会在这里发布整个product_table.html,我想它是直截了当的......主要是:

<table class="table table-striped table-hover">
    <thead>
        <tr>
            <th>product name</th>
            <th>price</th>
        </tr>
    </thead>
    <tbody>
        {% for product in page.object_list %}
            <tr>
                <td>{{ product.name}}</td>
                <td>{{ product.price }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>

表单中的数据通过 JS 收集并使用 AJAX 发送到 django。我没有使用正常的表单提交,因为我想避免页面重新加载(我知道这会解决这个问题)。

我确实尝试将上面提到的示例放在一起。除动态页面更新外,一切运行良好!

【问题讨论】:

  • 这件事有没有得到解决?我正在尝试做同样的事情。
  • 是的,我确实做到了。您的具体问题是什么?
  • 今天上午正在处理它。我试图弄清楚用户更新页面并将订单项放入......然后如何在不重新加载页面的情况下对项目列表进行排序。正如您所描述的,我有整个列表都可以与 HTMX 一起使用,而且一切都很好......除了我宁愿用户不必重新加载页面来重新排序列表。
  • 有人建议我做类似...ONCLICK="location.reload();"...这实际上确实有效。我只是想看看是否有其他方法可以解决这个问题。
  • 我在这里记录了我的问题....stackoverflow.com/questions/71147901/… 我似乎无法弄清楚迄今为止提供的回复。

标签: django htmx


【解决方案1】:

一些方法是删除 div 目标:

<div id="modal-create"></div>

然后在你的表体中写下删除的id:

<tbody id="modal-create">

您想要一些部分用于您的表格循环

{% for product in page.object_list %}
         {% include 'some_table_body_tr_partial.html' %}
{% endfor %}

您的部分可能包含如下内容:

<tr hx-target="this" hx-swap="outerHTML">
      <td>{{ product.name}}</td>
      <td>{{ product.price }}</td>
</tr>

这种方法有一个问题:表单的宽度将占用第一列的宽度。

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-15
    • 1970-01-01
    相关资源
    最近更新 更多