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
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page