Show list of categories - 30 days of Django

Show list of categories - 30 days of Django

/ #Django


In this part, we are going to show all of the categories in a sidebar on our template.

Getting the categories

The first thing we need to do here is to do some changes to the frontpage view. So open up task/views.py and make the following changes:

from django.shortcuts import render

from .models import Task
from category.models import Category # New, 1

def frontpage(request):
    title = 'This is a variable'
    tasks = Task.objects.all()
    categories = Category.objects.all() # New, 2

    return render(request, 'task/frontpage.html', {'title': title, 'tasks': tasks, 'categories': categories}) # Changed, 3

1. First, we import the category model.
2. Then, we get all of the categories from the database and assign it to a variable.
3. And to make it available for use in the template, we add it here in the dictionary.

Great, now we need to restructure the template a little bit. I know that it looks aweful, but it will be fixed a little bit later in the series. Open up the file called "frontpage.html" and make it look like this:

{% extends 'task/base.html' %}

{% block content %}
    <div class="frontpage">
        <h1>{{ title }}</h1>

        <div class="columns">
            <div class="column is-8">
                <h2>Tasks</h2>

                {% for task in tasks %}
                    <div>
                        <p>{{ task.title }}</p>
                    </div>
                {% endfor %}
            </div>

            <div class="column is-4">
                <h2>Categories</h2>

                {% for category in categories %}
                    <div>
                        <p>{{ category.title }}</p>
                    </div>
                {% endfor %}
            </div>
        </div>
    </div>
{% endblock %}

So here is a few new changes. We added some more divs, so it's easier to separate the tasks from the categories. Don't worry about the class names (columns, columns, is-8) yet, we will come back to that.

If you go to the browser again now, you will see the tasks listed there, but also all of the categories.

Table of contents

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.