Create Your Templates: Part 2
Take a look at how your template is displaying. Your project page is showing the title, description, and technology! Now let’s use the
for loop to display all of the projects. You’re going to add data through the Django shell. To start the Django shell, type the following:
$ python manage.py shell
You need to modify
models.py. You’re going to have to import:
>>> from projects.models import Project
Now, you’re able to create another instance of
>>> p = Project(title="test number 2", description="this is about more testing yes yes!", technology="Django", image="testproject.png")
00:00 Let’s go ahead and look at all these things displayed now. We’re here and this is how it looks like: we have our title, our description, and the technology—everything displayed in here. Now, how would it be if we have some more?
We don’t only have one project in there, but we want to see whether our
for loop works and displays all of the projects that are in there, so let’s go ahead and add some more data, again using the Django shell. To start a Django shell, if you remember, we go and type
python manage.py shell,
We can access the
.description or any other attributes that we have on it. So now, what we need to do next is we need to save it, so I call the
.save() method on it and now we should have it sitting inside of our database already.
So, without needing to exit any of this, I could just head back over and reload this. And there it is! You see? We have now two objects in our database. The
QuerySet returns both of them. We’re passing them forward to the template and our
for loop inside of the Django template renders the first one, and then the second one, picking out the different attributes of the object—there’s
.technology—and putting them into whatever HTML constraints we created for them. So, this one is inside of an
<h1> HTML tag, and this is a
<p> element in here, et cetera, et cetera.
Cool! So, that’s how we build templates in Django with the Django templating language. We’ve used template variables in here, and we’ve used template tags for code logic that look like this simple
for loop, in this case. Sweet! And that worked great.
In the next video, we’re going to get to know some more developing with error messages. We’re going to take a look at what we did with the
FilePathField, and then fix something that has come up here during development.
Become a Member to join the conversation.