Home/Blog/Web Development/Learn Django: A beginner's guide
Home/Blog/Web Development/Learn Django: A beginner's guide

Learn Django: A beginner's guide

10 min read
May 07, 2024

Django is an open-source web framework written in Python that allows quick development and simple, practical design. The developer community worldwide commonly uses it to create robust and maintainable web applications. For those who consider themselves beginners and wish to acquire web development skills, one of the first steps is to get acquainted with Django and learn backend development.

In this blog, we’ll explore Django’s fundamental concepts, providing explanations and practical examples to help you grasp its core principles effectively.

Getting started with Django#

Before diving into Django development, setting up our development environment properly is crucial. Here’s a step-by-step guide:

Installing Django#

We can install Django using pip, Python’s package manager. Open your terminal or command prompt and run the following command:

pip install django

Setting up a virtual environment#

It’s best practice to create a virtual environment for each Django project to isolate dependencies. Setting up a virtual environment in Python is a two-step process:

Creating a virtual environment#

Navigate to your project directory and use the following command to create a new virtual environment named myenv:

python -m venv myenv

Activating the virtual environment#

Depending on your operating system, use one of the following commands to activate the virtual environment:

  • On Mac/Linux:

source myenv/bin/activate
  • On Windows:

myenv\Scripts\activate

Creating a new Django project#

Once our virtual environment is activated, we can create a new Django project using the following command:

django-admin startproject myproject

This will create a new directory, myproject, with the following necessary files and folders:

myproject/
|-- myproject/
| |-- __init__.py
| |-- asgi.py
| |-- settings.py
| |-- urls.py
| |-- wsgi.py
|+-- manage.py
+-- venv/

Let’s go through each of them:

  1. myproject/: This is the root directory of our Django project. It usually shares the same name as our project.

  2. myproject/myproject/:

    1. Inside the root directory, there’s another directory with the same name as our project. This inner directory is where our project-specific Python code resides.

    2. __init__.py: This file tells Python that this directory should be considered a Python package. It’s empty in most cases but is required to make Python treat the directory as a package.

    3. asgi.py: Asynchronous Server Gateway Interface (ASGI) is a protocol used for asynchronous web servers in Python. This file configures our ASGI application, which is required for running Django applications on servers such as Daphne or Uvicorn.

    4. settings.py: This file contains all the configuration settings for our Django project. Here, we define database settings, static file configuration, middleware, installed apps, and much more.

    5. urls.py: This file is the URL configuration for our project. It maps URL paths to views. When a user accesses a specific URL on our website, Django uses this file to determine which view function to call.

    6. wsgi.py: Web Server Gateway Interface (WSGI) is a standard interface between web servers and Python web applications or frameworks. This file configures your WSGI application, which is required for running Django applications on servers such as Apache or Nginx.

  3. manage.py: This command-line utility lets us interact with our Django project. It allows us to perform various tasks, such as running the development server, creating migrations, and managing Django applications.

  4. venv/: This directory typically contains the virtual environment for our project. A virtual environment is a self-contained directory that contains a Python installation for a particular version of Python and several additional packages. It isolates our project’s dependencies from other projects and from the system-wide Python interpreter. This directory is created if we opt to create a virtual environment when setting up our Django project.

Django includes a built-in web server that is handy for local development, eliminating the need for additional installations. To run the project locally, simply execute the following command:

python manage.py runserver

Once the server runs, open the URL in a web browser: http://127.0.0.1:8000. We should see the expected page displayed.

Django installation output
Django installation output

Django projects are made up of apps, which are individual components that serve specific purposes.

Now, let’s create our appapp is web application that does someting. An app usually is composed of a set of models, views, and templates. in the project by running the following command:

django-admin startapp store

This will create a store app with the following necessary files:

myproject/
|-- store/
| |-- migrations/
| | +-- __init__.py
| |-- __init__.py
| |-- admin.py
| |-- apps.py
| |-- models.py
| |-- tests.py
| | +-- views.py
|-- myproject/
| |-- __init__.py
| |-- asgi.py
| |-- settings.py
| |-- urls.py
| |-- wsgi.py
|+-- manage.py
+-- venv/

Here’s an explanation of the directories and files within our store app:

  1. migrations/: This directory contains database migration files. Migrations are files generated by Django that manage changes to our database schema over time. They are created when we make changes to our models (defined in models.py) and need to synchronize those changes with the database. The __init__.py file indicates that this directory is a Python package.

  2. __init__.py: This file is an empty Python script that tells Python that the store directory should be treated as a Python package. It’s typically empty, but its presence indicates that the directory can be imported as a module.

  3. admin.py: This file registers our models with the Django admin interface. By defining classes in this file, we can customize how our models are displayed and interacted with in the Django admin.

  4. apps.py: This file defines our app’s configuration. It’s where we can specify metadata about our app, such as its name. Django uses this information to manage our app.

  5. models.py: This file is where we define the data models for our app. Models are Python classes that represent database tables. Each model class typically corresponds to a table in our database, and its attributes define the fields of that table. We define relationships between models and any additional methods or properties needed to interact with the data.

  6. tests.py: This file is used to write tests for our app. Django provides a testing framework that allows us to write unit, integration, and other tests to ensure that our app behaves as expected. We can define test cases and test functions/classes in this file to validate our app’s functionality.

  7. views.py: This file is where we define the view functions for our app. Views are Python functions or classes that handle web requests and return web responses. They typically interact with models to retrieve data, render templates to generate HTML content, and return responses to the client. Views control the logic and behavior of our app’s web pages.

These directories and files are essential to a Django app and define its functionality, structure, and behavior.

Now, we need to add this store app in the settings.py file, as shown below:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'store',
]

Understanding the MVC architecture#

In Django, a widely used web framework for building Python-based web applications, the MVC architecture is implemented with a slight variation called the Model-View-Template (MVT) pattern. However, the principles remain quite similar to MVC.

Let’s break down how Django implements this architecture.

Model #

In Django, models represent the application’s data structure. They define the fields and behaviors of the data stored in the database. Models in Django are typically Python classes that subclass django.db.models.Model. Each model class corresponds to a table in the database, and each class attribute represents a field. Models encapsulate data access and manipulation logic.

Defining models in Django#

Here, create the first model Product in models.py file as shown below:

from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()

The above code snippet defines a Django model named Product with three fields: name, price, and description. Here’s a breakdown of each field:

  1. name: This field is defined as a CharField with a maximum length of 100 characters. It represents the name of the product.

  2. price: This field is defined as a DecimalField with max_digits=10 and decimal_places=2, indicating that it can store decimal numbers with up to 10 digits and up to 2 digits after the decimal point. This field represents the price of the product.

  3. description: This field is defined as a TextField, which allows for larger text input compared to CharField. It represents the description of the product.

Now, to make changes to the database, we need to run a few commands:

python manage.py makemigrations

This will create a query to create the model structure in our database.

python manage.py migrate

This will execute the designed queries to form tables in our database.

Note: Always remember to execute these commands whenever you make changes to the models.py file that might affect your database table schema.

Fixtures#

We need some dummy data for the Product table. To add such data, Django allows us to define fixture files containing serialized data that can be loaded into the database. We can create a fixture file with dummy product data and then load it into the database. Here’s an example of a fixture file (products.json) in a folder store/fixtures:

[
{
"model": "store.product",
"pk": 1,
"fields": {
"name": "Product 1",
"price": 10
}
},
{
"model": "store.product",
"pk": 2,
"fields": {
"name": "Product 2",
"price": 20
}
},
{
"model": "store.product",
"pk": 3,
"fields": {
"name": "Product 3",
"price": 30
}
}
]

We can then load this fixture into our database using the loaddata management command:

python manage.py loaddata products.json

Template #

In Django, templates generate HTML dynamically. They allow us to separate the presentation layer from the business logic, in our views. Templates are written in HTML with embedded Django template language syntax, which allows us to include variables, loops, conditionals, and more.

We need to create a template file named product_list.html inside a directory named products within the templates directory of our Django app:

- myproject/
- store/
- templates/
- products/
- product_list.html

Inside product_list.html, we can use the Django template language to render the list of products:

<!-- product_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - ${{ product.price }}</li>
{% endfor %}
</ul>
</body>
</html>

The list of products is rendered as an unordered list (<ul>), with each product item represented within a list item (<li>). The template engine iterates over the products array provided by the view, dynamically generating HTML markup for each product. This ensures that the presentation of the product list is generated dynamically based on the data retrieved from the database, maintaining separation between the presentation layer (HTML) and the business logic (database query) of the application.

View#

In Django, a view is responsible for processing HTTP requests and returning appropriate HTTP responses. Views can be implemented as functions or classes. Here’s an example of a Django view implemented as a function:

from django.shortcuts import render
from .models import Product
def product_list(request):
# Retrieve all products from the database
products = Product.objects.all()
# Pass the products to the template for rendering
return render(request, 'products/product_list.html', {'products': products})

In the above Django view function, product_list, the primary task is to retrieve all products from the database using Product.objects.all(), which queries the database for all instances of the Product model. Once the products’ information is obtained, the view prepares to render it within an HTML template.

To pass this information to the template, the view utilizes the render function, which takes the request, the path to the template file, and a dictionary containing data to be passed to the template. In this case, the dictionary includes a key-value pair where the key is 'products' and the value is the list of products retrieved from the database.

Once the template receives this data, it utilizes Django’s template language to iterate over the list of products using a loop construct. The template processing engine recognizes the embedded template tags and expressions, including variables, loops, conditionals, etc., and renders the HTML dynamically based on the provided data.

Now, we need to create URLs for accessing the views.

URLs#

URLs define the mapping between web addresses and views. To create the URLs, create the urls.py file in the store directory and add the following code:

from django.urls import path
from .views import product_list
urlpatterns = [
path('products/', product_list, name='product_list'),
]

Next, we need to include the URLs of the store in the main project URLs. To do this, open the myproject/urls.py file in the main project directory and add the following code:

from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('store/', include('store.urls')), # Assuming 'store' is the name of your app
]

Run the server again and check your first Django application output.

Retrieved product list on HTML page
Retrieved product list on HTML page

Conclusion#

As we conclude our journey through Django, reflecting on what we’ve accomplished together is important. We’ve covered the main aspects of Django, from setting up our development environment to building our first project and app. Along the way, we’ve shared in the joys of discovery and the satisfaction of overcoming challenges. As we part ways, let’s celebrate the knowledge we’ve gained and the confidence we’ve developed.

Congratulations! You’re all set to begin your journey of learning Django. Keep expanding your knowledge through our courses, followed by practical applications. We suggest regularly undertaking new projects to reinforce and broaden your skill set. 


Written By:
Ammar Ahmad Farid
 
Join 2.5 million developers at
Explore the catalog

Free Resources