Build A Django Blog — Part 01
Recently I started mentoring new programmers and realized often there is a lack of a good foundation before starting to learn Django, so I wanted to share this. I use this structure in all my professional and personal Django projects.
1. The Basics
Local environment set-up
Note: the $ dollar sign is the command line prompt, all commands in this article are intended to be typed after the $ prompt.
- Install Apple’s Xcode package
$ xcode-select --install
- Install MacOS package manager Homebrew and confirm it installed correctly.
$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"$ brew doctor // if this works Homebrew installed correctly
- Install Python 3
Python 2 is installed by default on MacOS, since Python 2 is now deprecated we’ll need to install Python 3.
$ brew install python3
To confirm the correct version was installed run the following command
$ python3 --version
Python 3.7.7
- Install Git
$ brew install git
- Install virtualenv to isolate package requirements per project
$ pip3 install virtualenv
- Install virtualenvwrapper for a better experience when managing virtual environments
pip3 install virtualenvwrapper
Also don’t forget to add the following to your bash_profile. Create one if you don’t have it.
$ vi ~/.bash_profile
Copy and paste the following. To exit VIM hit the ESC key on your keyboard and then type :wq or :q! to exit without saving your changes.
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv
export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
2. Create a Django project
- Create a Sites directory to keep your projects organized and in one place:
$ cd
$ mkdir Sites
$ cd Sites
- Initialize a new virtual environment for your project
$ mkdir django_app
$ cd django_app
$ mkvirtualenv django_app
Once the virtual environment is activated your terminal should look similar to this.
(django_app) ~/Sites/django_app $
- Create a new Django project called django_app and install it in the current directory
$ django-admin startproject django_app .
At this point your project should look like this:
├── manage.py
├── django_app
|── __init__.py
│── settings.py
│── urls.py
└── wsig.py
Test things out to make sure everything is running smoothly. Let’s run Django’s local webserver.
$ python manage.py runserver
If you visit http://127.0.0.1:8000 you should see the following:
3. Create a blog app
Django uses the concept of projects and apps to keep code clean and readable. A single Django project contains one or more apps within it that all work together to power a web application.
$ python manage.py startapp blog
Add the blog app to your settings.py at the bottom of INSTALLED_APPS
# django_app/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.apps.BlogConfig', # new
]
This is what your project should look like at this point.
├── manage.py
├── blog
|── __init__.py
│── admin.py
│── apps.py
│── migrations
| └── __init__.py
│── models.py
│── tests.py
└── views.py
├── django_app
|── __init__.py
│── settings.py
│── urls.py
└── wsig.py
4. Add Templates
Start off with base.html, we’ll extend this template so we can inherit from it later on. We’ll use a project-level template pattern, it is one of my preferred patterns because it makes a project less confusing and keeps our code more clean and maintainable.
$ mkdir templates
$ touch templates/base.html
$ touch templates/home.html
Update settings.py so Django knows where to look for our templates
# django_app/settings.py
TEMPLATES = [
{
...
'DIRS': [os.path.join(BASE_DIR, 'templates')],
...
},
]
Update base.html, note that the code between {% block content %} and {% endblock content %} can be filled by other templates.
<!-- templates/base.html -->
<html>
<head>
<title>Django app</title>
</head>
<body>
<header>
<h1><a href="{% url 'home' %}">Django app</a></h1>
</header>
<div>
{% block content %}
{% endblock content %}
</div>
</body>
</html>
Update home.html and extend base.html which wraps this content block.
<!-- templates/home.html -->
{% extends 'base.html' %}
{% block content %}
{% for post in object_list %}
<div class="post-entry">
<h2><a href="">{{ post.title }}</a></h2>
<p>{{ post.body }}</p>
</div>
{% endfor %}
{% endblock content %}
5. Add the views to add functionality
# blog/views.py
from django.views.generic import ListView
from .models import Postclass BlogListView(ListView):
model = Post
template_name = 'home.html'
6. Create database models for a blog post
# blog/models.py
from django.db import modelsclass Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()def __str__(self):
return self.title
Don’t forget to run the migrations
$ python manage.py makemigrations $ python manage.py migrate
6. Add the URLs to display our pages
# blog_project/urls.py
from django.contrib import admin
from django.urls import path, include # newurlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')), # new
]
You’ll end up with something simpler if you followed this tutorial. I’m working on a blog so my template looks like this. You can easily grab it from the repo here.
I hope this helps you on your journey. Tune in for my next post as I start on day 01 of this #100DaysOfCode challenge. I’ll be going over theming, styles, and JavaScript.
Thank you and don’t forget to follow me/give me some claps!