Next Lesson: Lesson 8: URLs in Django
What are templates in Django? And, how will we apply these templates to our code? You’ll about to find out in this lesson!
In the last lesson, we’ve agreed that it would be terrible to put all our HTML code inside this string here:
But where will we put all our HTML code? We’ll put it in a separate template. A template is a way for you to separate your HTML file from the views.py file.
Create a template
We need to create a new folder that’s gonna contain our templates. Of course, we’ll name this folder templates:
After hitting ENTER, click that folder and create a new file. We’ll name this file home.html:
ENTER:
How will we send the contents of this file to the user? Let’s do something inside our settings.py to tell Django where to find these templates.
settings.py
On our settings.py, look for the TEMPLATES:
See it? Let’s put ‘templates’ inside these brackets ([]):
Good.
render
Now we’ll add something inside our views.py:
Copy what I did on Line 2:
Now that we have render imported, we can now change the HttpsResponse on Line 5 with render. And, we’ll replace ‘Hello’ with request and then our HTML file:
Nice. But we’re not finished yet; our home.html is still empty.
HTML
Let’s put these inside our home.html:
You’re familiar with these HTML heading tags because we’ve used them last time. Now, let’s refresh our browser:
Perfect! I will teach you some of the basics in HTML besides heading tags as we go. Did you know that we could have some Python code inside our HTML file?
Python Inside a HTML file
Let’s go back to our views.py:
An example of Python code that we can put here is a dictionary:
In this dictionary, start is the key and Enter text: is the value. After that, let’s go back to the home.html and put 2 pairs of curly braces {{}} like this:
This now allows you to write some Python code. Let’s put our dictionary‘s key in between these braces:
Let’s see if this works:
Nice! Before we conclude this lesson, I’ll ask you a question: Did you understand the flow of our code? If not, that’s okay; we’ll have a recap.
Recap
When someone types in the URL of our homepage, urls.py will see if it matches with anything it has:
Because the user just entered our homepage’s URL (hence, the empty string), this will take them to the views.py and look for the homepage function there:
Now, this function runs taking the user to our home.html file:
Finally, this file will show its contents to the user:
Epic! Hopefully you understood the flow of our code. But if you didn’t understand something on the flow, please post your questions below in the Comments section and I’ll try my best to answer it.