Laughing Blog Tutorial Part 1-The Project Structure

published on: | by cindy In categories: Tutorial Series , Django

My journey as a programmer has taught me one valuable lesson: To effectively learn how to write and understand programming concepts, never underestimate the value of building real-life applications. I remember staying up late trying to grasp the concepts of programming. But to make the concepts stick, I embarked on a journey to create achiengcindy.com and share my journey with you all.

The aim of this tutorial series, The laughing blog, is to create a fully functional blog in Django.

Overview

We will implement functionalities such as :

  • Registration and Authentication
  • Newsletter
  • Sending Emails
  • Comment system
  • Social media share
  • Blog.list of our blogs and a detailed view of each blog post

The code can be found on github.

If you follow through, you too can create your own blog or even earn from it.

Prerequisites

  • Basic Git Knowledge
  • A github or bitbucket account.If you dont have,create one for free on github or bitbucket
  • Django basics.If you are new to django check my previous tutorial on Django Environment in Linux .
  • Text Editor of choice.I will be using Sublime Text.You can download it here.

Setting up the laughing-blog project

In this tutorial, you will learn how to create Django project structure, learn git and some very useful python libraries such as whitenoise and python decouple.

I will use pip and virtualenv to create the project structure however, you can use pipenv

let's get started

Create a folder and name it tutorial where our project will be stored.

 mkdir tutorial && cd tutorial

Nice, next we have to create a Virtual Environment for our project

 virtualenv env -p python3

specify the python version .We will use python3

To use our virtual environment we must activate it

 source env/bin/activate

After activating the virtual environment. Install Django using the command below:

$ pip3 install django

We are going to create the project named laughing_blog by using the command below:

 $ django-admin startproject laughing_blog

If you change Directory to laughing_blog, you should have a structure like this:

laughing_blog
--laughing_blog
----__init__.py
----settings.py
----urls.py
----wsgi.py
--manage.py

Change the outer laughing_blog to src ( it is just a container that holds our project). To make sure that django is successfully installed run server using the command

python manage.py runserver
and if all went well,you should see this page:

Now we are all set to start writing codes. However, there are some configurations and libraries I want to introduce.

Python-decouple

Python Decouple will help us separate sensitive settings from the project.Storing passwords and other sensitive information such as secret key in settings.py is not a great idea and that is why we will use python-decouple. Install it using the following command:

pip3 install python-decouple

After successfully installing Python-decouple, create a .env text file on your project's root directory.

Using Python Decouple

.env is the file where all the sensitive information will be stored. So far, we need to store our secret key and debug status. It should look like this:

SECRET_KEY = your key
DEBUG = True

settings.py

Import config object and place it below import os.

  from decouple import config

This is a snippet from my settings.py.

import os
from decouple import config

Replace the secret key and debug with the following:

SECRET_KEY = config('SECRET_KEY'')
DEBUG = config('DEBUG', cast=bool)

Git

It is important to push your changes to a remote repository. Initialize git using:

git init   // Initializes git

Next, we want git to ignore some files with secret information such as the settings, database, etc.Now,create a gitignore file and add the .env, *.pyc ,db.sqlite3 and any other text file in it.To create gitignore use the command:

touch .gitignore

Next, let's add all our changes, commit and push

git add *    //adds all changes
git commit -m "initial commit"
git remote add origin https://github.com/<your username>/laughing_blog.git 
git push -u origin master

Templates

Html is a static language used to display data on the browser. Django is dynamic and offers a way to display HTML dynamically by using the powerful in-built template tags. Django templating enable us to separate the presentation of a document from its data. We could simply embed HTML in python code, but it is not a good idea because:

  1. In large projects, it is common to have front-end developers handling HTML and back-end developers handling python. If HTML is hard-coded in python code, it would be difficult for both developers to edit the same file at the same time without interference.
  2. In a single application, you may need to write many lines of HTML codes and troubleshooting the code can be messy if HTML is hard-coded in the python code.

Setting up Django Templates

We want to create the templates directory in the projects' root directory. We can achieve this by modifying the settings.TEMPLATE-DIRS by adding this:

"DIRS": [os.path.join(BASE_DIR, 'templates')],

The DIRS defines a list of directories where Django should look for template source files.

let's create the templates directory and then create a file called base.html to include the project's main HTML structure

mkdir templates
cd templates && touch base.html

snippet for base.html

    {% load staticfiles %}
    <!Doctype html>
    <html>
    <head>
        <title> Laughing blog</title>
    </head>
    <body>
       {% block content %}{% endblock %}
    </body>
    </html>

How to Serve Static Files in Django

Web applications will need additional files like CSS, scripts, and Images for the application and user-uploaded content such as profiles pictures. These files can be categorized as:

  1. Static files: Resource used by the application such as scripts, images
  2. Media files: These are the content uploaded by the user, say user profile picture. We will talk about this later.

Configuring Static Files

Managing static files in django can be complicated especially if you are not familiar with Django.In settings.py make sure django.contrib.staticfiles in INSTALLED_APPS.In, Most cases,it is already defined.

INSTALLED_APPS = [
...
'django.contrib.staticfiles',
...
]

STATIC_URL

In settings.py you will find this line of code

   STATIC_URL = '/static/'

This is where Django serves static files for a particular app in your project. Django allows you to have several static folders in a project. For this project, we will create just one static folder in the root project directory so let's configure staticfiles-dirs

STATICFILES_DIRS

Let's say you have a project and most apps share static assets like styling or images, or in addition to the static files tied to a particular app, you require additional static assets then defineSTATICFILES_DIRS.

The STATICFILES_DIRS tuple tells Django where to look for static files that are not tied to a particular app.

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]

In this case, we just told Django to also look for static files in a folder called static in our project's root folder, not just in our apps.

Then create the static directory in the project's root folder

$ mkdir static

Serving Static Files in Development

When django.contrib.staticfiles is installed,running runserver command automatically serve the static files otherwise serve them manually by:

Project's urls.py

from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
urlpatterns = [
...
]
if settings.DEBUG:
    urlpatterns +=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

STATIC_ROOT

This is the storage folder for every static files after running the collectstatic command.It collects all the static files in one place. Let us tell django to collect all our static files in a folder called staticfiles

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

This is very important in production andwhitenoise handles this very well.

Whitenoise

Managing static files in production is even more complicated,at-least it was for me! To manage our static files with less hustle,we will install a 3rd party library whitenoise

To install whitenoise, run:

 pip3 install whitenoise

To use whitenoise in Django.We edit settings.py by adding it to MIDDLEWARE_CLASSESbelow the django SecurityMiddleware

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...
]

To enable compression to add the following :

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Conclusion

We created Virtual Environment, Installed Django, installed Python-decouple and created our template and static files directory. We also create gitignore file and added the .env text file we created. Meet you in the next tutorial!