【发布时间】:2020-01-18 05:13:07
【问题描述】:
我必须使用 Ajax 和 Django 视图更新模板上的数据。 在模板中有按钮,shell 根据视图响应更新表上下文。
我已经阅读了几个类似的回复:1、2、3、4、5、6,但找不到解决方案。
模板.html
<button type="submit" class="btn btn-warning vindication" value="vindication">Vindication</button>
<table class="table" align="center">
<thead class="black">
<tr>
<th>Data</th>
</tr>
</thead>
<tbody class="data">
{% for client in invoices_all_data %}
<tr>
<td>{{ client.data }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function(){
$(".vindication").click(function(){
var vindication_type = $(this).attr("value");
$.ajax({
url: "/invoices/vindication_filter/",
data: {
vindication_type : vindication_type,
},
type: "POST",
success: function(response) {
$('#data').html(response);
}
});
});
});
</script>
按钮点击数据发送到views.py函数后处理:
def vindication_filter(request):
if request.method == 'POST':
vindication_type = request.POST['vindication_type']
# filter data
client_data = MonitoringUsers.objects.all()
invoices_all_data = MonitoringUsers.objects.none()
for client in client_data:
if client.get_all_invoices():
invoices_all_data = invoices_all_data | MonitoringUsers.objects.filter(
user_id=client.user_id, pay_status=vindication_type)
return TemplateResponse(request, "template.html", locals())
到目前为止,代码正在运行,但我不知道如何将处理后的数据 [invoices_all_data - QuerySet] 返回到主 template.html?
感谢您的任何建议。
【问题讨论】: