Reputation: 912
I am trying to add a search feature for my Django project, but I have a problem knowing how to write Django Template in the Javascript Innerbox.
I have an Item model as following:
class Item(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(blank=False, upload_to=upload_design_to)
price = models.DecimalField(decimal_places=2, max_digits=100)
discount_price = models.DecimalField(decimal_places=2, max_digits=100, blank=True, null=True)
timestamp = models.DateTimeField(default=timezone.now)
Item list view as following:
class ItemListView(ListView):
model = Item
paginate_by = 12
template_name = "store/product_list.html"
ordering = ['-timestamp']
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["qs_json"] = json.dumps(list(Item.objects.values()),cls=DjangoJSONEncoder)
return context
I have the following Script:
<script>
const data = '{{qs_json}}'
const rdata = JSON.parse(data.replace(/"/g, '"'))
console.log(rdata)
const input = document.getElementById('search_here')
console.log(input)
let filteredArr = []
input.addEventListener('keyup', (e)=>{
box.innerHTML = ""
filteredArr = rdata.filter(store=> store['title'].includes(e.target.value))
console.log(filteredArr)
if (filteredArr.length > 0){
filteredArr.map(store=>{
box.innerHTML += `<b>${store['title']}</b><br>` <------------------------------- Replace
})
} else {
box.innerHTML = "<b>No results found...</b>"
}
})
</script>
I am trying to replace the innerHTML <b>${store['title']}</b><br>
with
<div class="col-4 mb-3">
<div class="card h-100">
<a href="{{item.get_absolute_url}}">
<embed src="{{ item.image.url }}" class="card-img-top" alt="..."/>
</a>
<div class="card-body">
<h5 class="card-title">{{ item.title }}</h5>
<p class="card-text">
{% if item.description %}
{{ item.description }}
{% endif %}
</p>
</div>
<div class="card-footer">
<small class="text-muted">{{ item.timestamp }}</small>
</div>
</div>
</div>
But the result is that nothing is showing broken Image and it is not reflecting the item information
My question is how do I show the information related to each item
Upvotes: 1
Views: 1182
Reputation: 320
This solution is much easier:
result_html = loader.render_to_string(
'template_name.html', {'object_list': object_list}
)
data = {
'result_html': result_html,
}
return JsonResponse(data)
Upvotes: 1