1

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(/&quot;/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

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Could add a little more explanation as I am new to Javascript
by this solution, you can use Ajax to fetch data from Django. then append the result_html to your page.
This needs a different script code, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.