Previous Lesson: Lesson 43: Creating the Projects Page in Django
In this lesson, we’re gonna be creating the blog page in Django. You may think that you know how to do this already. But I’m going to teach you something new.
Now, it’s time for creating our Blog page! In our portfolio‘s urls.py:
We’ll type these (addition Line 17 and the whole Line 26):
So we’ve imported include on Line 17. And then we created a path for our blog on Line 26. You may ask, “where in the world did you get that code Zedd?” Take a look at the documentation here from Line 1 down to Line 15:
Have you noticed the one on Line 14 before?
Yes, that’s where we have got it. If it’s in the documentation, it’s probably the best to use. Now, on our blog‘s urls.py:
So we’ve imported views.py using a dot(.). And then on Line 6, I got rid of the admin/ path and changed it with a new path. Then in our blog‘s views.py:
Good. I think you now understand why we are doing that blog/blogs.html, am I right? Now, what’s our next move?
Right, we’ll create a new file that would be inside the templates/blog folder like this:
Then hit ENTER:
Good. Let’s do this so that we just know if things are really working good now:
Now let’s take a look at our localhost:8000/blog:
Good. “Yes, we copy.”
Flow of Code
Were you able to keep up with the flow of our code? Here, let me explain it to you because we have some new things that we’ve learned so far.
Let’s start here:
If the user enters localhost:8000/blog, that would not go to a views.py. Instead, it will go to another urld.py, but this time, it’s the blog‘s urls.py.
So it will go here:
On Line 3, we have imported the views.py using a strange line of code. Did you take a look at the dot reference that I’ve told you about earlier? That reference explains what that dot (.) was for.
It says: “The single dot is a convention from command line applications. It means the current directory. In terms of Django it stands for the directory/module the current file is on.”
In other words, we’re just telling Django that the file that we’ll be importing is just inside the current folder. For instance, the views.py is in the blog folder, which is the same with the urls.py–their on the same folder.
So, it will then look for the blogs function here on blog‘s views.py:
Now the code from our views.py refers to our blogs.html, which is this one here:
Hopefully, you understood all that. This may be confusing at first so if you have any questions, just post them at the Comments section below. And I’ll do my best to answer them.
But I’ll go ahead you because you may ask this same question: “Yeah, but why do we need a different file for the blog URLs? Can’t we just directly put the URLs on the portfolio‘s urls.py, instead of taking a look on another file like the blog‘s urls.py?”
Good question. You’ll find soon find out on the next lessons. But before you head there, make sure that you commit these changes to GitHub: