Showing contents from the model - 30 days of Django

Showing contents from the model - 30 days of Django

/ #Django


Now it's time to get some data from the database and render it in the template we have created.

A few days ago, we created our first database model and it looked like this:

Class Task(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    is_done = models.BooleanField(default=False)

So this is currently the information we have for our tasks. What we want to do in this part is to get the data from the database, and print it in the template (frontpage.html).

Let's begin by opening the task/views.py file. Right now, the file looks like this:

from django.shortcuts import render

def frontpage(request):
    title = 'This is a variable'

    return render(request, 'task/frontpage.html', {'title': title})

Here, we want to import the Task model and a few more things. Make these changes to the file:

from django.shortcuts import render

from .models import Task # New, 1

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

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

I have added comments on the lines that I changed.
1. Here we import the database model.
2. Here we define a variable called "tasks". Then we use the Task model to get all the objects (tasks).
3. On this line, we appended the tasks together with the title. So now, both of these will be available in the template.

Now that everything in the backend is done, we can do some changes to the template. Now it looks like this:

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

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

        <p>This is just a hard coded paragraph!</p>
    </div>
{% endblock %}

Then, below the paragraph, we want to loop through the tasks:

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

So what we do here is that we use a for loop to iterate throught them. Accessing a property on a model is as easy as just saying "{{ task.title }}". We could also print the task.is_done, or task.description if we wanted that.

Let's do one more change to the backend, so we only get task with "is_done=True".

tasks = Task.objects.filter(is_done=False)

So instead of using ".all()", we now use ".filter()". Here we can pass in filters that Django should use for the query. Later in this series, we will go through more like this.

If you now go to the admin interface and set a task to "Done", it will no longer appear on the frontpage.

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.