- You’ve installed Django. If not,
$ pip install django.
- You’ve created the project directory, like so:
$ mkdir webapp
$ cd webapp
- You’ve created the Django project directory structure.
$ django-admin startproject webapp .
1 Creating the
We name our app within the
webapp project as
2 Configuring the home page
- Add the blog app to the
- Configure the home URL in
- To create the home view, add the
homeview function in
- That function must refer to the home template (
- Because the
templatesdirectory was newly created, Django doesn’t know anything about it, so let’s register it at
blog folder should contain the following:
admin.py: Gives access to the admin dashboard for configuring our models
models.py: Create and configure our models (a.k.a. database entities)
views.py: Create the views as functions that renders the template file
3 Creating the View
We first create the base template so that the succeeding templates can use it as their base page template (this is known as template inheritance)
A view function takes a request and returns a response. 1
4 Adding CSS file
Static files such as images, assets, CSS, scripts, etc. are placed in their own folder inside a folder named
static. This folder doesn’t exist so let’s create it. Then we let Django know about it through an environment variable in
5 Creating the Model
Models define the structure and the behavior of our data2. In order for it to be shown in the admin dashboard, we must register it first in
__str__() method returns a human-readable representation of our model (usually text).
6 Admin dashboard
We don’t have access to the admin dashboard (Django doesn’t allow anonymous logins to the admin page) so we create a user with all permissions enabled.
7 Creating a slug
To generate our slug automatically, we override the
save() method and place our slug generator code in it.
8 Setting the URL to use the newly generated slug
app_nameis the namespace for our URLs here. For example, to reference a detail page we can use
- To capture our URL values (i.e. the slug), we surround the ‘slug’ keyword with angle brackets (
9 Set the blog app URL
We want to view the blog detail page using this pattern:
10 Continuing with the details view
Now that we’ve set the URL to the pattern that we like, let’s create the
details handler to take care of the logic such that if the page can not be found, we display a corresponding page (i.e. 404 page).
11 Creating the template
Best case scenario, the page should exist. We create the actual page that the users will see.
12 Displaying all posts in the home page
And finally, we list all our blog posts in the home page.