I have a Customer model in my Django application. New users are constantly being added to this model in the background and I want to list these customers dynamically with AJAX. But I cannot figure it out. How can I do that?
def ajax_view(request):
obj = Customer.objects.filter(company=request.user.company)
customers = []
for customer in obj:
customers.append(customer)
data = {
"obj": customers
}
return JsonResponse(data)
html
<h3 id="status"></h3>
<script>
var refresh = setInterval(function() {$.ajax({
url: "{% url 'user:ajax_customer' %}",
type: "GET",
dataType: 'json',
success: function (data) {
if (data) {
console.log(data);
console.log(status);
document.getElementById("status").innerHTML = data.obj;
}
}
});}, 1000);
</script>
I try to do that but It gives an error:
TypeError: Object of type Customer is not JSON serializable
CodePudding user response:
def ajax_view(request):
obj = list(Customer.objects.filter(company=request.user.company).values())
return JsonResponse({'data':obj})
JQUERY
<script>
var refresh = setInterval(function() {$.ajax({
url: "{% url 'user:ajax_customer' %}",
type: "GET",
dataType: 'json',
success: function (data) {
let html = ''
data.data.forEach((element, index) => {
html = `<tr>
<td>${element.columname}</td>
<td>${element.columnname}</td>
<td>${element.columnname}</td>
<tr>`
})
$('#status').html(html)
}
});}, 1000);
</script>
HTML
<table>
<thead>
<tr>
<td>columname</td>
<td>columnname</td>
<td>columnname</td>
</tr>
</thead>
<tbody id="status">
</tbody>
</table>