Django for Dummies

Kevin Lizarazu
9 min readNov 4, 2023

--

Web frames, the backbone of web developers and the shot of espresso for developers and casual hobbyists like you and I. If you’re at all like me, you’re probably scrounging around the internet looking for a deeper and facilitated understanding of the inner workings of web frames, specifically the python-based web frame that is Django!

We’ll run through the concepts and follow a short demo in this article.

Photo by Brecht Corbeel on Unsplash

What even is a web frame? The internet defines this tool as a software for the development of web applications including web services, web resources, and web APIs through libraries.

There are many web frames that exist already, each built to work with specific languages and are responsible for popular applications and websites as shown below.

Notable Frameworks

Many of these frameworks follow the similar concept of Model, View, Controller (MVC) or Model, View, Template (MVT).

  • Model: represents data models and business logic (database)
  • View: handles the visible components such as or UI (HTML)
  • Controller: manages user inputs and communications (APIs)

What’s special about Django is that in their architecture the view is paired with controller as those handle the visible components and routing through URLs. A separate section is created for templates that serves as the dynamic representation of View to allow for efficiency and separation of concerns in organizing our HTML, JS, and CSS components.

MVT Django Architecture

Django Philosophy

To understand the inner workings of Django it’s also important to know the history and intent behind this popular web frame.

Django was invented to mee the fast-moving demands of newsroom deadlines while satisfying tough requirements of experienced web developers to create fast, secure, scalable, and versatile products.

Below are the primary pillars that need to be considered to use Django the way it’s intended and to its full advantage:

  1. Don’t Repeat Yourself (DRY) — avoid redundancy by keeping critical code and information in one place
  2. Less Code is Better — minimize boilerplate code and focus the concise/expressive code that accomplishes more with fewer lines (abstraction)
  3. Loose Coupling — be able to change or replace individual parts without affecting the entire application for scalability and modularity
  4. Explicit > Implicit — clear and implicit code is always the best choice to teach and have other developers understand code using this framework
  5. Test — Django comes with a tests folder that should be used for test-driven development in which objectives or tests are made before any coding is done

Django Setup

Django is a python library that can be installed using the pip installer, and can only be used in a virtual or conda environment. Before starting this section make sure to have the following installed:

  1. Create the anaconda and activate the environment
conda create --name movow python=3.10
conda activate movow

2. Install the Django library using pip

pip install django

3. Create a project and application folder

mkdir movow
cd movow
django-admin startproject movow
django-admin startapp movow_app

4. Run the server by calling the manage.py in the same directory

python manage.py runserver

Once these setup steps are completed you should observe this on your locally hosted server (port 8000 by default), and your directory to look like this:

If you want a high-level understanding of the relationships between these files before we get into it, below is a good diagram to keep in mind.

Projects and Applications

A project in Django brings together all the working parts of a full application/website. A project can house multiple applications that work together to make working website.

In this example, the project is Facebook, and the applications that make it work are Profile, News Feed, and Groups. Each of these applications serve one function and should be self-sufficient submodule of the project like a standalone python module.

To determine if you need another application, to put it in simple terms:

If you can’t explain what it does in one sentence, it’s probably an app

Project Files Breakdown

Application Files Breakdown

** asterisks represent the critical files for modification

Templates and Static

Django has default folder paths that can be overridden, such as where a view goes to render HTML information. In order to to do this we need to create the template and static folders in the application directory.

  • Templates: houses all HTML files
  • Static: houses all CSS, JS, and any media

For the purposes of our demo later on in this article, add the following:

  • Any image named to test.png in the imgs folder
  • A CSS file named style.css with the following code to modify the body
body {
font-family: sans-serif;
color: red;
}
  • An HTML file named index.html that adds header text and an image
<!DOCTYPE html>

<html>

<head>
{% load static %}
<title>MOVOW</title>
<link rel="stylesheet" href="{% static 'movow_app/css/style.css' %}">
</head>

<body>
<h1>Index Page!</h1>
<br>
<img width="500px" height="500px" src="{% static 'movow_app/imgs/test.png' %}">
</body>

</html>

Views (Control)

Views is responsible for linking pages to an HTML template, sending a queryset response as per the Controller requirements of request and response when users interact with the website.

Typically the main method of displaying content to users is to render HTML responses, but we take advantage of Django’s main pillar of writing less code to do more so we aim to use the generic tool to substitute the some boilerplate code that comes with the render function.

Generic Code (Left) vs Boilerplate Render (Right)

In this example we use generic’s ListView method, which in a URI would represent the general list of items. The alternative to the generic method is DetailView which focuses on the specific information of one item, typically adding on to the URI with a slug that is the resource ID.

Typical URL pattern involving domain, URI, resourceID (optional), and query string (optional)

To summarize the django.views’ generic method:

  • List View — represents a list of objects to display to the user
  • Detail View — displayes one object in full detail with all fields displayed

URLs

To route various views in our application, we need to create a urls.py file in our application directory that is capable of routing URLs to different pages.

In order to have the project recognize the routing that happens in each individual application, we need to modify the project’s urls.py by adding the path that includes the routing we established to views in the application.

In addition to adding the application’s URL routing to the main project, we must make sure the project is aware that there is an application in the project, and we do this by modifying the project’s settings.py.

With this we’re prepared to head into our demo!

Demo

Now that we’ve created a project and an application, we’ll run the server and observe that we were in fact able to view the index.html file we made earlier. Before that, make sure to run these commands to save our work and run the server:

python manage.py makemigrations
python manage.py migrate
python manage.py runserver
  • Migrations — Django’s way of propagating changes you make to your model (similar to git add/commit)
  • makemigrations — creates new migrations based on changes made to the models concerning the database (add)
  • migrate — responsible for applying migrations (commit)

If everything goes according to plan, you should observe this prompt in your terminal:

If problems do persist, make sure you troubleshoot what the is present in the prompt. Follow the link provided in the prompt that leads to the local server to observe this page:

This is ok! It’s all because we didn’t make a landing page for our project, but we have made a landing page for our application (movow_app). These errors are present because Debug=True was set in settings.py of the project. To observe our index.html we made earlier, add “/movow_app” to the URL of the local server.

Success! Here we observe that everything we specified in our index.html file is present, as well as the elements we connected in our static folder. This structure is important for ordering Django, and now that you are able to see the fruits of your work, continue to modify as you please for a static website.

Models

Single definitive source of information containing essential fields and behaviors of stored data. Models map to a single database table, in which each column is a field of an element, and each row is an entry containing those fields.

We can observe which database engine we’re using by looking into our DATABASE field in the project’s settings.py to manage our relational tables.

Django is optimized to work with relational databases like PostgreSQL, as its model system includes its own Object Relational Mapper (ORM) to call for objects without the conventional string inputs. Django is actually able to work with other supported databases like MongoDB, but only through packages like pymongo or djongo.

For the purpose of this article we won’t get into making models because of the nature of each individual project, so below is an example of two tables (models) with their own fields and even a relation field between a Question and Choice model for a polls project.

Django Admin

One of the advantages of Django is that this web frame anticipates the intent for administrative actions by creating an admin interface for models interactions. This means that if admin user created a superuser, they would have access to the admin page to manually add entries into the models table, automatically saved in whichever database is used.

To create a superuser and enter admin view, follow these steps:

  1. Create a superuser with the following commands on terminal

2. After running the server, append “/admin” to the base localhost URL

3. After logging in you should be able to see this view

You might notice that you can’t see your models at this very moment, in order to fix this, go into the admin.py file and register the models you want to see by adding this code:

from .models import *

admin.site.register(Model1)
admin.site.register(Model2)

This code imports the models from the application’s models.py and registers them to the admin view.

Testing and Debugging

This is the last and most important part of Django, the aspect that drives test-driven development. Django makes it really easy to be able to test behaviors to ensure proper deployment of websites.

Two important aspects about the tests.py file is that:
1. For every test generated, a temporary database is created and deleted
2. Every test is required to start with “test” as the first word in the def name

We won’t go into testing too much right now, but here’s an example following the Question model that tests its behaviors.

Thank you for making it this far, and good luck with making your Django web application, I hope I was able to help facilitate your understanding as much as it did mine!

--

--

Kevin Lizarazu
Kevin Lizarazu

Written by Kevin Lizarazu

Computer Engineering graduate from Virginia Tech aiming to break into R&D and Web Development through software. Enjoys playing guitar and competing in tennis.

No responses yet