I have a container (
<div class="card-body">
) and I want to insert elements from the database dynamically (using AJAX)
However, I require a dynamic solution as I will be adding content on-the-fly and Django template tags alone are not sufficient.
Is there a way to achieve this from within the ajax success function?
index.html
:
{% extends 'base_generic.html' %}
{% load static %}
{% block content %}
{% get_current_language as LANGUAGE_CODE %}
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '/todo_ajax/',
type: 'get',
success: function(data) {
alert(data);
},
failure: function(data) {
console.log('An error occurred');
}
});
});
</script>
<div class="wrapper">
<!-- Index Content -->
<div id="content">
<div class="row row-cols-1 row-cols-md-3 g-4 mb-5">
<div class="col">
<div class="card h-100">
<div class="card-header" id="toDoHeader">
... (truncated)
</div>
<div class="card-body">
{% for o in some_list %}
<div class="cardItem cardItemIndex" class="mb-3">
<div class="row">
<div class="col">
<h6 class="card-title">{{ o.title }}</h6>
</div>
</div>
<div class="row">
<div class="col">
<p class="card-text">{{ o.description }}</p>
</div>
</div>
<p class="card-text to-do-footer">{{ o.start_date }} - {{ o.end_date }}</p>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
views.py
@login_required
def todo_ajax(request):
response = dict()
if request.method == 'GET':
to_do_list = ToDoList.objects.all().filter(user=request.user)
data = serialize("json", to_do_list)
return HttpResponse(data, content_type="application/json")
return HttpResponse('')
models.py
from django.db import models
from django.contrib.auth.models import User
class ToDoList(models.Model):
title = models.CharField(max_length=60)
description = models.TextField()
start_date = models.DateTimeField(null=True)
end_date = models.DateTimeField(null=True)
user = models.ForeignKey(
User,
null=True,
blank=True,
on_delete=models.SET_NULL,
)
In essence, how can I dynamically generate this portion when the AJAX method is invoked:
<div class="card-body">
{% for o in some_list %}
<div class="cardItem cardItemIndex" class="mb-3">
<div class="row">
<div class="col">
<h6 class="card-title">{{ o.title }}</h6>
</div>
</div>
<div class="row">
<div class="col">
<p class="card-text">{{ o.description }}</p>
</div>
</div>
<p class="card-text to-do-footer">{{ o.start_date }} - {{ o.end_date }}</p>
</div>
{% endfor %}
</div>