Laughing Blog Tutorial Part 1-Project Structure
Tags: laughingblog, pipenv, whitenoise, pythondecouple
Published: 2018-11-30 09:32:45

---
title: Laughing Blog Tutorial Part 1-Project Structure
published: true
description: Django project structure
tags: laughingblog, pipenv, whitenoise, python-decouple
series: Laughing Blog Tutorial.
canonical_url: https://achiengcindy.com/blog/2018/04/07/laughing-blog-tutorial-part-2-handling-django-forms/

---

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 <a href="https://achiengcindy.com" target="_blank">achiengcindy.com</a> 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

The code can be found on <a href="https://github.com/achiengcindy/laughing_blog" target="__blank">github</a>. 

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 <a href="https://github.com" target="__blank"> github</a> or  <a href="https://github.com" target="__blank"> bitbucket</a>
+ Django  basics.If you are new to django check  my previous tutorial on <a href="https://achiengcindy.com/blog/2018/02/27/how-set-django-environment-linux-beginners/" target="__blank">Django Environment in Linux</a> .
+ Text Editor of choice.I will be using Sublime Text.You can download it <a href="https://www.sublimetext.com/3" target="__blank">here</a>.

#### 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  <a href="https://achiengcindy.com/blog/2018/04/23/pipenv-new-python-packaging-tool/" target="__blank">pipenv</a>

**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 <strong>activate</strong> 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:

``` python
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 <pre><code class ="python">python manage.py runserver</code></pre> and if all went well,you should see this page:

![](https://i.imgur.com/F3GEYtx.png)

 Now we are all set to start writing codes.However, there are some configurations and libraries I want to introduce. 
#### Python-decouple
<code>Python Decouple</code> will help us separate sensitive settings from the project .Storing passwords and other sensitive information such as <code>secret key</code> in <code>settings.py</code> is not a great idea and that is why we will use <a href="https://pypi.python.org/pypi/python-decouple" target="__blank">python-decouple</a>. Install it using the following command:

    $ pip3 install python-decouple
After successfully installing <code>Python-decouple</code>, create a .env text file on your project's root directory.

**Using Python Decouple**
<strong>.env</strong>

This is the file where all  the sensitive information are stored.So far,we need to store our secret key and debug status.It should look like this: <pre><code class="python">SECRET_KEY = your key
DEBUG = True</code></pre> 

<strong>settings.py</strong>

Import `config ` object   and place it below <code> import os</code>.
         
      from decouple import config
This is a snippet from my <code>settings.py.</code>

    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 used to display data on the browser and not python.
Django is a web framework offers a way to display HTML dynamically by using the powerful in-built <strong> template tags</strong>. Remember HTML is static while python is dynamic. 
Django templating enable us to separate the presentation of a document from its data. 
We could embed HTML on 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 <strong>base.html </strong> to include the project's main html structure

    $ mkdir templates
    $ cd templates
       base.html

snippet for base.html
``` 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  <code> user-uploaded content</code> 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 <code>settings.py</code> make sure <code> django.contrib.staticfiles</code> in  <code>INSTALLED_APPS</code>.In, Most cases,it is already defined.

**STATIC_URL**

In <code>settings.py </code> 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 <strong>staticfiles-dirs</strong>

**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 define<code>STATICFILES_DIRS</code>.

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 <code> django.contrib.staticfiles</code> is installed,running <code>runserver</code> command automatically serve the static files otherwise serve them manually by:

Project's <code>urls.py</code>

    from django.conf import settings
    from django.conf.urls.static import static
    urlpatterns = [
         ... 
     ] 
     + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

**STATIC_ROOT**

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

    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
This is very important in production and<code>whitenoise</code> 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 <a href="http://whitenoise.evans.io/en/stable/django.html" target="_blank">whitenoise</a>

To install whitenoise, run:

     pip3 install whitenoise

To use whitenoise in Django.We edit <code>settings.py</code> by adding it to <code>MIDDLEWARE_CLASSES</code>below the django <code>SecurityMiddleware</code>

    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!