After sending an HttpResponse from views.py to an HTML page, I encountered an issue where only the JSON object is displayed instead of the expected details in the HTML format.
The current appearance of the page after the request: https://i.sstatic.net/yFeUf.png
This is how the data should ideally be displayed: https://i.sstatic.net/ZZuHI.png
views.py
def tracker(request):
if request.method == "POST":
oid = request.POST.get('oid', '')
email = request.POST.get('email', '')
try:
order = Orders.objects.filter(order_id=oid, email=email)
if len(order) > 0:
update = OrderUpdate.objects.filter(order_id=oid)
updates = []
for item in update:
updates.append({'text': item.update_desc, 'time':item.timestamp})
response = json.dumps(updates, default=str)
return HttpResponse(response)
else:
return HttpResponse({})
except Exception as e:
return HttpResponse({})
return render(request, 'shop/tracker.html')
tracker.html
{% include 'shop/basic.html' %}
{% block body %}
<div class="container">
<div class="col my-4">
<h2>My Awesome Cart Tracker - Enter your Order ID and Email address to track your order</h2>
<form method="POST" action="#" id="trackerForm">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="Oid">Order Id</label>
<input type="text" class="form-control" id="oid" name="oid" required="">
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Email</label>
<input type="email" class="form-control" id="inputEmail" name="email" required="">
</div>
</div>
<button type="submit" class="btn btn-primary">Track Order</button>
</form>
</div>
<div class="col my-4">
<h2>Your Order Status</h2>
<div id="items" class="my-4">
<ul class="list-group my-4" id="items">
Enter your order ID and Email and click Track Order to find details about your order!
</ul>
</div>
</div>
{% endblock %}
{% block js %}
<script>
$('#trackerForm').submit(function (event) {
$('#items').empty();
var formData = {
'orderId': $('input[name=oid]').val(),
'email': $('input[name=email]').val(),
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
}
$.ajax({
type: 'POST',
url: '/shop/tracker/',
data: formData,
encode: true
})
.done(function (data) {
updates = JSON.parse(data);
if (updates.length > 0 & updates != {}) {
for (i = 0; i < updates.length; i++) {
let text = updates[i]['text'];
let time = updates[i]['time'];
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
${text}
<span class="badge badge-primary badge-pill">${time}</span>
</li>`
$('#items').append(mystr);
}
}
else {
mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
Sorry, we are not able to fetch this order ID and email. Kindly recheck the Order ID and email.</li>`
$('#items').append(mystr);
}
});
event.preventDefault();
});
</script>
{% endblock %}