1

I'm trying to build a page with all of the model's categories and associated entries in one view. I followed tips from here django class based views for all categories with all entires and here Get all categories and items in category but I still can't get it to work. Any ideas ?

-- models

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

class Feed(models.Model):
    name = models.CharField(max_length=100)
    url = models.CharField(max_length=100)
    category = models.ForeignKey(Category)
    user = models.ManyToManyField(User)

    def __unicode__(self):
        return self.url

-- views

def category_page(request):
    object_list = Category.objects.all()
    context = {'object_list': object_list,}
    return render(request, 'category_page.html', context)

-- template category_page.html

{% block content %}
{% for category in object_list %}
    {{ category.name }}
    {% for entry in category.entry_set.all %}
        {{ category.name}}
    {% endfor %}
{% endfor %}
{% endblock content %}

I'm getting list of all categories displayed but no entries.

thanks -M

2 Answers 2

0

Here

{% for entry in category.entry_set.all %}
    {{ category.name}}
{% endfor %}

should be

{% for entry in category.feed_set.all %}
    {{ entry.name}}
{% endfor %}

{{ category.name}} inside the forloop for entries is what is not displaying the correct name.

Also, what is entry_set ? If you are not specifying a related_name, you need to use the lower-case model name to get the related objects (feed_set in this case).

Something like this:

category.feed_set.all

Summing it up,

{% block content %}
{% for category in object_list %}
    {{ category.name }}
    {% for entry in category.feed_set.all %}
        {{ entry.name}}
    {% endfor %}
{% endfor %}
{% endblock content %}

You can read more on related objects here

0

If this is your actual code, the problem is variable names in your template.

{% for category in object_list %}
    {{ category.name }}
    {% for entry in category.feed_set.all %}
        {{ entry.name}}
    {% endfor %}
{% endfor %}

Specifically, you refer to entry_set, but that's not the reverse name for the relationship since your model name is Feed rather than Entry and you haven't declared a non-default related_name argument.

Also, you're re-printing your category name instead of the name of the Feed instances.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.