B
B
bwylla2020-05-22 16:41:18
Django
bwylla, 2020-05-22 16:41:18

How to display an element of an object?

class Product(models.Model):
    title = models.CharField(max_length=200)
    text = models.TextField(blank=True)
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.title

def product_list(request):
    products = Product.objects.all()
    return render(request, 'shop/product/list.html', {'products': products})

{% block content %}
<p>{{ products }}</p>
{% endblock %}

The output is , if you write products.title in the template, then nothing is displayed at all <QuerySet [<Product: Coffee>]>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2020-05-22
@bacon

Go offsite and read how a QuerySet differs from an object, or at least try to think a little.

M
Maxim Alyukov, 2020-05-23
@mvxmvl

{'products': products}
is a context, and there are a lot of objects in it, since you pulled everything out of the database. By calling {{ products }} directly, you won't get a response for a specific element. Everything needs to be looped through.
{% for some in products %}
    {{ some.title }}
    {{ some.text }}
    {{ some.created_date }}
    {{ some.published_date }}
{% empty %}
    <p>Нет данных</p>
{% endfor }%

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question