I have model in models.py:
class Category(models.Model):
name = models.CharField('Nazwa Kategorii', max_length=100)
slug = models.SlugField('Odnośnik', unique=True, max_length=100)
icon = models.ImageField('Ikonka Kategorii', upload_to='icons',
blank=True)
class Meta:
verbose_name = "Kategoria"
verbose_name_plural = "Kategorie"
def __unicode__(self):
return self.name
And i want to do View with list of all Categories:
views.py
class CategoryList(generic.ListView):
model = models.Category
context_object_name = 'category_list'
category_list = CategoryList.as_view()
In base.html i have:
{% for entry in category_list %}
<li><a href="#">{{ entry.name }} </a></li>
{% endfor %}
But it doesent return any categories.
What i miss?
I want to add in basic template Menu with category list..
You should not expect to have category_list context variable set for base.html. CategoryList class view uses template ‘< app_name >/category_list.html’ by default. You can change this by setting template_names attribute for this view.
If you want to have ‘category_list’ context variable accessible in all templates (which is possible, taking into account that you try to use in base.html) you need to define context processor and add this variable to the context.
Context processor you need can look like this:
Once you have this function defined somewhere in your code (it is a good practive to put in in context_processors.py in related app) you need to register this in TEMPLATE_PROCESSORS settings variable (see above link to django docs for reference).
Last thing to mention here is that you should consider caching query results as this code will be exectued on each request.