P
P
PiggyPig2017-09-24 12:27:39
Django
PiggyPig, 2017-09-24 12:27:39

Why is the image not displayed on .values()?

views.py

def article(request, c_name):
    context = {
        'page_img': Article.objects.filter(category=c_name).values('image').first()
        # ...
    }
    return render(request, 'app/page.html', context)

page.html
...
<img src="{{ page_img.image.url }}">
...

Another model text field would work, but with the image some kind of nonsense.
No matter how I tried - I do not understand how to make it work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2017-09-24
@deliro

values('image') will return you what it should - the value of the field in the database. And this is the relative URL of the image.

{'page_url': Article.objects.filter(category=c_name).values('image').first()['image']}
...
<img src="{{ page_url }}">
...

This is how it will work. But it would be more concise to write it like this:
{'page_url': Article.objects.filter(category=c_name).values_list('image', flat=True).first()}
...
<img src="{{ page_url }}">
...

PS The reason why it is preferable to use values/values_list before only (of course, provided that only values ​​are needed, and not a model object):
str(Photo.objects.values('image').query)
Out[7]: 'SELECT "catalog_photo"."image" FROM "catalog_photo" ORDER BY "catalog_photo"."position" ASC'
str(Photo.objects.only('image').query)
Out[8]: 'SELECT "catalog_photo"."id", "catalog_photo"."image" FROM "catalog_photo" ORDER BY "catalog_photo"."position" ASC'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question