在最近在一些简单的 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。我没有使用正常的表单提交,因为我想避免页面重新加载(我知道这会解决这个问题)。
我确实尝试将上面提到的示例放在一起。除动态页面更新外,一切运行良好!