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 Project
:
>>> 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?
00:16
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
,
00:40
and this opens up the Django console for us. So now I’m able to interact using Django’s default settings already opened up. I want to be able to add something to our projects
model.
00:55
I’ll open this up so we have a reference. I’m going to have to import it first, so I go to projects.models
, remember? from projects
…
01:09
and now I’m able to create another Project
instance that has a title
,
01:25
technology
—still "Django"
—and an image
.
01:33
I’m just going to give it the same image for now. We’ll talk about these images in a bit. Okay. I created this Project
. We can take a look at it. Yes, the instance exists.
01:46
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.
02:03
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 .title
and .description
, .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.
02:42
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.
02:59
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.
03:15 Remember, that’s totally normal and fine, and we’re going to learn how to deal with such situations. See you in the next video, and get ready for debugging!
Gascowin on Oct. 20, 2019
…or better still, give a user the chance to add this info from the web interface.
Martin Breuss RP Team on Oct. 21, 2019
Hei @Gascowin! Yes, there are ways to do both of these things. However, they both open up yet another chapter that can be a great next step in your web dev journey :)
Adding Data With a Script
All the code in Django is just Python, and Django Models, which provide the interface through Django’s ORM, are just classes. That means that you can interact with your Database directly by writing Python code.
Depending on where you have your data stored, you could write a script that takes e.g. CSV or JSON as an input file, fits the data into the Django Models by creating class instances (just as you did in the Django shell in this part of the course), and then uploads it to the database using the .save()
method on the instance.
That said, there are also tons of Django plugins that implement such functionality, so if you have a standard task to achieve, there’s probably a solution out there. E.g.:
Allowing Users to Add Data
This one can be a little tricky, but it’s a great next step! You’ll have to work with HTML Forms and Django Forms. These are your link for allowing user input from the front-end of your page.
It’s a common functionality for many websites, so for many web dev projects you’ll eventually need to learn how to do this. However, before you go down that road, here’s one more option to consider:
Using the Django Admin for Data Input
Check out the video on the Django Admin Interface later in this course. Django comes pre-packed with this handy admin interface that allows admins to easily input data through the front-end.
You can customize it, have different permissions for different groups etc. If you want, you can read more about all the possibilities it has in the official docs.
reblark on Nov. 2, 2019
Hmm. Your html file, all_projects did not include images, yet in the shell, you entered p.image. There was no attirbute “image” and nothing showed up on the page. In models.py you do have an “image.” Was the shell line supposed to create a line in the html file and, if so, why didn’t it?
Martin Breuss RP Team on Nov. 3, 2019
Hei @reblark. Adding an entry to your database using the Django shell should never make any changes to the HTML file. Imagine the HTML file as the filter-structure that defines which pieces of information from the database you’ll actually want to display on the page. There can be more in there, but in the template you choose what to show.
You’ve added an .image
attribute to your Project
object because that’s a required attribute for any instance of that type of object. It is required because you defined it to be when writing the Project
model in models.py
. So that’s why you need to enter it in the Django shell.
Our filter (=the HTML and Django templating language code in all_projects.html
), however, isn’t (yet) written in a way to do anything with the .image
attribute of a project.
Watch the next video to see how to add the image by changing the code in all_projects.html
.
Lokman on Jan. 7, 2020
Hi @Martin ! previous video tutorial we insert the data information to database. Then if I want do amend, how to access back to do the amend? Since we create P1 as object with shell django or I just override that object(p1)?
Martin Breuss RP Team on Jan. 7, 2020
@VeLoct84 Yes, you can amend the information of your database entry also through the Django shell, similar to how you created it. However, you will first need to fetch it from the database to use it as a Python object with Django’s ORM, then edit it as needed, and finally save it back to the DB.
Let’s take a look at how to do that:
1) Fetch The Data
As you can see in the Video, each project gets an auto-incrementing ID assigned automatically upon creation. Django does that for you, and you can see the ID the project object has in the database e.g. through the default output you can also see on the screen in the video:
<QuerySet [<Project: Project object (1)>, <Project: Project object (2)>]>
This output tells you that you have 2 rows in the database, one with the ID of 1
and the other one with the ID of 2
.
Now you want to change the first row, so you’ll need to gain access to the data stored there through the ORM. The code for doing that with Django’s ORM is as follows:
p1 = Project.objects.get(pk=1)
You’re passing the primary key, which in this case is the ID of the object, as an argument to the get()
method.
Now you have access to the stored data in a Python object, e.g.:
>>> p1.technology
'Django'
2) Edit The Data
Having access to the data in a Python object allows you to edit it in the familiar way:
p1.technology = "Python"
By using the code above, you can double-check that the data has changed.
3) Save The Data
Finally you’ll have to save the changed object data back to your DB. You do that with the same command that you use for saving a new object:
p1.save()
The Django ORM object remembers the unique identifier and therefore updates the existing row in your DB, instead of creating a new object.
Hope this helps and clarifies how to edit existing DB entries via the Django shell.
Lokman on Jan. 8, 2020
Base on tutorial course:
>>> db = Project.objects.all()
>>> p1 = db[0] # indexing list
>>> p1.technology
>>> 'django'
>>> p1.technology = 'python'
>>> p1.save()
>>> p1.technology
>>> 'python'
I think primary key method can simplified the code
>>> p1 = Project.objects.get(pk1)
>>> p1.technology
>>> 'django'
>>> p1.technology = 'python'
>>> p1.save()
>>> p1.technology
>>> 'python'
Martin Breuss RP Team on Jan. 8, 2020
Yes, these are two different ways of doing the same thing, and the second one can be cleaner and more intuitive if you know the primary key of the object you want to access. Thanks for summing it up :)
Two Notes
Typo In Argument Passing: The first line of the second code block needs to read:
p1 = Project.objects.get(pk=1)
You’re passing the number 1
as a keyword argument to the get()
method. That’s most likely just a typo, but I wanted to make sure no one gets confused when trying to use your code :)
Verifying Changes: Accessing the object (p1
) again after calling p1.save()
doesn’t tell you anything about changes to the content of your database. You are again just checking up on the p1
object you created and edited before.
If you want to verify that the data changed in the database, you’ll need to make another call to the database before, like so:
>>> p1 = Project.objects.get(pk=1)
>>> p1.technology
'django'
>>> p1.technology = 'python'
>>> p1.save()
>>> # now we fetch the database row again to see whether it changed
>>> p1_check = Project.objects.get(pk=1)
>>> p1_check.technology
'python'
Lokman on Jan. 9, 2020
>>> # now we fetch the database row again to see whether it changed
>>> p1_check = Project.objects.get(pk=1)
>>> p1_check.technology
'python'
Ok, that’s awesome to check the latest update in our database. Thanks!
kumimochi on July 29, 2020
after I added the second ‘project’ on the shell, I can’t connect anymore.
Martin Breuss RP Team on July 30, 2020
HI @kumimochi what is the error message that you see? Try to exit the shell and go back in again, it might solve the problem. Otherwise please give some more info on what is happening and what feedback Django is giving to you :)
alcuinog on Nov. 26, 2020
Could you please provide me with a link to the list of Django shell commands and list of Django template language ?
Thanks. Alcuino
Bartosz Zaczyński RP Team on Nov. 27, 2020
@alcuinog If you type one of Django’s built-in commands, you’ll get the list of available subcommands:
$ django-admin
Type 'django-admin help <subcommand>' for help on a specific subcommand.
Available subcommands:
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
(...)
To get more details, you can try the help
command:
$ django-admin help shell
Alternatively, use the --help
flag:
$ django-admin shell --help
The official Django documentation is pretty decent. You’ll find everything you need there, including help on the Django template language:
thomasseidling on Dec. 28, 2020
Hi Martin, . Great content. Going through the course I was wondering whether you could provide a working Portfolio project as a sample. The once that’s in the course materials section is only partially written.
The reason for asking is that I am visually impaired and therefore can only follow the audio but not the video. Piecing together certain things from the audio only is quite challenging and time consuming, e.g. ‘now we change this down here …’ only makes sense together with visual information. If I could use a finished project as reference point that would be very helpful.
thanks in advance
Ricky White RP Team on Dec. 28, 2020
Hi @thomasseidling,
Thanks for your feedback. I’ll make sure Martin gets it. We have a written version of this course which might work better for you, in this instance, if you use a screen reader? This is the link to the article: realpython.com/get-started-with-django-1/
There is also downloadable source code linked in the article. I hope that helps.
Ricky
thomasseidling on Dec. 29, 2020
@Ricky, thanks, very useful!
Martin Breuss RP Team on Dec. 29, 2020
Hi @thomasseidling, thanks for your feedback and thanks @Ricky for posting the article link.
I’ll definitely try to be spell out more descriptively what I’m doing on screen for my next videos. 👍
Become a Member to join the conversation.
Gascowin on Oct. 20, 2019
Very well taught material good sir! Thanks for showcasing how data can be added to the database from the Django terminal. I imagine there should be a way to add these more efficiently?