Home > Software engineering >  Django image dosen't show when searching?
Django image dosen't show when searching?

Time:01-25

I have an inventory app with products and its name, photo.

I query the records in HTML page and all works fine and the images showing.

when i try to search the result come without the photo.

View:

def inventory_search_view(request):
    query = request.GET.get('q')
    product_search = Inventory.objects.filter(name__icontains = query).values()
    print(product_search)
    context = {'object_list': product_search}
    return render(request, 'inventory_search.html', context = context)

HTML:

    {%for object in object_list %}
    <div >
        
        <img src="{{object.image}}" alt="{{object.name}}" />
        
    
    <div >
        <h2> Description</h2>
        <ul>
            {{object.description}} 
            
            
        </ul>
    </div>
    </div>
    
    </div>
{%endfor%}

search form:

    <form action="search/">
        <input type="text" name="q">
        <input type="submit" value="Search">

    </form>

Thanks in advance.

CodePudding user response:

Why are you using .values()? Why not pass the queryset to the page? In the page you should also do object.image.url I believe.

def inventory_search_view(request):
    query = request.GET.get('q')
    product_search = Inventory.objects.filter(name__icontains=query)
    print(product_search)
    context = {'object_list': product_search}
    return render(request, 'inventory_search.html', context=context)

And in your template:

{%for object in object_list %}
    <div >
        
        <img src="{{object.image.url}}" alt="{{object.name}}" />
        
    
        <div >
            <h2> Description</h2>
            <ul>
                <li>{{object.description}}</li>
            </ul>
        </div>
    </div>
    
{% comment %} </div> This shouldn't be here, or you're missing some code in your question {% endcomment %} 
{% endfor %}
  • Related