0

最近在一些简单的 HTMX 任务中取得成功之后,我想通过一个动态更新表的模态字段来扩展adamchainz django-htmx 示例。我不确定我是否返回了正确的东西,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"})

网址.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。我没有使用正常的表单提交,因为我想避免页面重新加载(我知道这会解决这个问题)。

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

4

1 回答 1

0

一些方法是删除 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>

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

于 2022-02-25T01:02:31.860 回答