Previous Lesson: Lesson 40: How to Put Copyright Symbol on Website

Are we going to hardcode each and every one of our hobbies in the HTML? No, we’ll be using for loop to show data from models. I’ll teach you how to do it.

In this lesson, we’re going to learn how to show our hobbies here on our homepage, instead of having these cards:

First, this chunk of code (from Line 79 to Line 93) is for a box hobby. And, this will be the only card that we’ll leave:

In other words, all these other code that you’ll see highlighted below (from Line 94 down to Line 215):

As you scroll down, you’ll see a pattern with this code. Thus, these are the other box hobbies. After selecting all lines from Line 94 down to Line 215 (if my code is exactly as yours), then now press DELETE:

So, this will be the only box (or card) hobby that we have:

Let’s see:

Nice. But as we can see in our sketch, we don’t want to have those View and Edit buttons. Additionally, we don’t want to have that 9 mins:

So we’ll delete these lines here:

DELETE:

After deleting, let’s check our card:

Nice. Now what? Are we going to hardcode each hobby card? That would be a waste of time! I have something better and I’m going to teach it to you. and I’m going to teach it to you. and I’m going to teach it to you.

Looping through the hobbies from database

Have you already guessed why I keep looping the words “and I’m going to teach it to you”? You’ll soon find out. Let’s go to our views.py:

And type these in:

On Line 2, we said from .models, which refers to our models.py. And then we’ve imported Hobby from that same file. The Hobby.objects will get all the hobby objects we’ve made from our database and then assigned this to a variable, hobbies.

Once we have these job objects, we’ll passed them as a value to our dictionary with the keyhobbies‘. Now here on our home.html, type what’s on Line 85, Line 89, and Line 93. Make your code look exactly like this:

Yup, this is a for loop. We are using a for loop here. This will loop through all summaries of every hobby we’ve got from our database (that’s what Line 89 does):

Let’s see what this does on our hobby cards:

Nice. Now, what about the images? Well, we’ll do this:

Now this should display our image for each hobby card. Let’s see:

That’s incredible! That’s how using for loop to show data from models saves us more time, strength, and effort. Now, let’s commit this to GitHub!

I hope you have enjoyed and understand how we’ve created our portfolio’s homepage because on the next lesson, we’ll create the Projects page! See you there!

Next Lesson: Lesson 42: Instructions for the Projects Page

Leave a Reply

Your email address will not be published. Required fields are marked *