简体   繁体   中英

Python - displaying images in Django

I'm new with django and i'm trying to create project, but i got a problem with displaying images. I have a html table with checkboxes and after selecting an object i wish to display image on next page but i can only get broken image.

i can display image this way :

<img src="{{ MEDIA_URL }}bird.png" class="img-responsive" style="width: 60px; height:80px; margin:auto;" />

but then obviously this image will be shown in every object. but in this way what i use in index page it wont find any images:

<img src="{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" />

this is my views.py

def selected(request):
    tags = request.GET.getlist('selected')
    return render(request, 'tag/selected.html', {'all_tags':tags})

if i use:

def selected(request):
    tags = request.GET.getlist('selected')
    all_tags = Tags.objects.all
    return render(request, 'tag/selected.html', {'tags':tags, 'all_tags':all_tags})

then it will find the images but then it will also show all the images even if i select only one. this has been my problem for awhile now so please if anyone could help me i would really appreciate that

I'll try to interpret your question correctly! but tell me if I'm wrong:

Your Tags model looks something like this:

class Tags(models.Model):
    tag_image = models.ImageField(upload_to='/somewhere')
    ...

If you want to get only the selected few, in your view you'll do something like this:

def selected(request):
    tag_ids = request.GET.getlist('selected')
    selected_tags = Tags.objects.filter(id__in=tag_ids)
    return render(request, 'tag/selected.html', {'tags': selected_tags})

and then, in your template, you want something like this:

{% for tag in tags %}
<!-- tag is a single tag in this context -->
<img src="{{ tag.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" />
{% endfor %}

Hope it helps to clarify how Django works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM