我一直在尝试了解 ajax 和 Datatables 在 Django 中的工作原理。但是,正如标题所说,我的数据列表是原始显示在我的视图中。
我将把我的代码放在这里,以便您可以帮助我了解缺少或错误的内容。
我的列表视图:
class SampleList(LoginRequiredMixin, ListView):
model = Samples
def render_to_response(self, context, **response_kwargs):
data = list(self.get_queryset().values())
return JsonResponse(data, safe=False)
我的模板:
{% extends 'partials/base.html' %}
{% load static %}
{% block title %}Samples List{% endblock title %}
{% block content %}
<div class="main-panel">
<div class="content-wrapper">
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<!-- partial -->
<h2>Here are all samples: </h2>
<h1>Samples</h1>
<table id="samples-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
//I don't know if here must be empty
</tbody>
</table>
<script>
$(document).ready(function() {
// Initialize DataTable
$('#samples-table').DataTable({
// Replace "yourmodel-list/" with the URL of your view
"ajax": {
"url": "{% url 'samples:samplelist' %}",
"dataSrc": "data" // Property name that holds the array of records in the JSON response
},
"columns": [
{"data": "id"}, // Column for ID
{"data": "sample_code"}, // Column for Name
{"data": "reception_date"}, // Column for Date
],
});
});
</script>
{% comment %} <div>
<ul>
{% for sample in object_list %}
<li>{{ sample.sample_code }} | <a
href="{% url 'samples:sample-update' sample.pk %}">edit</a>
<a href="{% url 'samples:sample-delete' sample.pk %}">delete</a>
</li>
{% empty %}
<li>No samples yet.</li>
{% endfor %}
</ul>
<p>
<a href="{% url 'samples:sample-add' %}">add a sample</a>
</p>
</div> {% endcomment %}
</div>
<!-- main panel ends here-->
</div>
{% endblock content %}
和 jquery 库:
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
你能帮我理解这是如何工作的吗?谢谢你。
它应该自动显示我的数据表中的数据,因为 ajax 从我的视图中获取数据。
因为你渲染了一个 JSONResponse。 您应在
之前归还您的模板return render(request, template_name, context={"data":data})