Django is a high-level Python web framework that simplifies web development with clean, pragmatic design and robust features. This guide introduces Django's core concepts, highlights its benefits, and explores why it’s ideal for building secure and scalable web applications.
Django is a framework consisting of a set of components that solve common web development problems. Django components are loosely coupled, which means they can be managed independently. This helps separate the responsibilities of the different layers of the framework; the database layer
knows nothing about how the data is displayed, the template system knows nothing about web requests, and so on.
Django offers maximum code reusability by following the DRY (don’t repeat yourself) principle. Django also fosters rapid development and allows you to use less code by taking advantage of Python’s dynamic
capabilities, such as introspection.
You can read more about Django’s design philosophies at click link
Main framework components
Django follows the MTV (Model-Template-View) pattern. It is a slightly similar pattern to the well-known MVC (Model-View-Controller) pattern,
where the template acts as the view and the framework itself acts as the controller.
The responsibilities in the Django MTV pattern are divided as follows:
Model: This defines the logical data structure and is the data handler between the database and the view.
Template: This is the presentation layer. Django uses a plain-text template system that keeps everything that the browser renders.
View: This communicates with the database via the model and transfers the data to the template for viewing.
The framework itself acts as the controller. It sends a request to the appropriate view, according to the Django URL configuration.
When developing any Django project, you will always work with models,views, templates, and URLs.
The Django architecture
The Django architecture
WEB BROWSER
| HTTP Request
| HTTP Response
Django
URL DISPATCHER
TEMPLATE
VIEW
MODEL
DATABASEExplanation of the flow:
- WEB BROWSER sends an HTTP request to Django.
- The URL DISPATCHER receives the request and determines which VIEW should handle it.
- The VIEW processes the request and may interact with the MODEL to fetch data.
- If necessary, the VIEW will use the TEMPLATE to format the response.
- The response is sent back to the WEB BROWSER as an HTTP response.
- If required, the MODEL interacts with the DATABASE to retrieve or store data.
This is how Django handles HTTP requests and generates responses:
1. A web browser requests a page by its URL and the web server passes the HTTP request to Django.
2. Django runs through its configured URL patterns and stops at the first one that matches the requested URL.
3. Django executes the view that corresponds to the matched URL pattern.
4. The view potentially uses data models to retrieve information from the database.
5. Data models provide data definitions and behaviors. They are used to query the database.
6. The view renders a template (usually HTML) to display the data and returns it with an HTTP response.
Django also includes hooks in the request/response process, which are called middleware. Middleware has been intentionally left out of this diagram for the sake of simplicity.
How to Create Django Project
Run the following command in your shell prompt:
django-admin startproject mysiteLet’s take a look at the generated project structure:
mysite/
manage.py
mysite/
__init__.py
asgi.py
settings.py
urls.py
wsgi.pyThe outer mysite/ directory is the container for our project. It contains the following files:
manage.py: This is a command-line utility used to interact with your project. You won’t usually need to edit this file.mysite/: This is the Python package for your project, which consists of the following files:__init__.py: An empty file that tells Python to treat themysitedirectory as a Python module.asgi.py: This is the configuration to run your project as an ASGI application with ASGI-compatible web servers. ASGI is the emerging Python standard for asynchronous web servers and applications.settings.py: This indicates settings and configuration for your project and contains initial default settings.urls.py: This is the place where your URL patterns live. Each URL defined here is mapped to a view.wsgi.py: This is the configuration to run your project as a Web Server Gateway Interface (WSGI) application with WSGI-compatible web servers.
Applying Initial Database Migrations
Django applications require a database to store data. The settings.py file contains the database configuration for your project in the DATABASES setting. The default configuration is a SQLite3 database. SQLite comes bundled with Python 3 and can be used in any of your Python applications. SQLite is a lightweight database that you can use with Django for development.
If you plan to deploy your application in a production environment, you should use a full-featured database such as PostgreSQL, MySQL, or Oracle. You can find more information about how to get your database running with Django at:
https://docs.djangoproject.com/en/5.0/topics/install/#database-installation
Your settings.py file also includes a list named INSTALLED_APPS that contains common Django applications added to your project by default. We will go through these applications later in the Project Settings section.
Django applications contain data models that are mapped to database tables. You will create your own models . To complete the project setup, you need to create the tables associated with the models of the default Django applications included in the INSTALLED_APPS setting. Django comes with a system that helps you manage database migrations.
To apply the initial migrations, open the shell prompt and run the following commands:
cd mysite
python manage.py migrateThe preceding lines are the database migrations that are applied by Django. By applying the initial migrations, the tables for the applications listed in the
INSTALLED_APPS setting are created in the database.
Running the Development Server
Django comes with a lightweight web server designed to help you run your code quickly without the need to configure a production-ready server. When you run the Django development server, it continuously monitors your code for changes. It automatically reloads whenever a change is detected, saving you the effort of restarting the server manually after every code modification.
However, be aware that it may not detect certain actions, such as adding new files or performing some configurations manually.
Start the development server by typing the following command in the shell
python manage.py runserverYou should see something like this:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
January 01, 2024 - 10:00:00
Django version 5.0, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.Now, open http://127.0.0.1:8000/ in your browser. You should see a page
stating that the project is successfully running
Confirming the Server Is Running
If you take a look at your console, you will notice the GET request performed by your browser:
[01/Jan/2024 10:00:15] "GET / HTTP/1.1" 200 16351 Each HTTP request is logged in the console by the development server. Any errors that occur while the development server is running will also be displayed in the console, making it easy to track and debug issues.
You can also run the Django development server on a custom host and port or specify a particular settings file using the following command:
python manage.py runserver 127.0.0.1:8001 --settings=mysite.settings
This flexibility allows you to tailor your development environment according to your needs.
When working with multiple environments that require different configurations—such as development, testing, staging, and production—you can create a separate
settingsfile for each environment. This approach helps keep your configurations clean, organized, and environment-specific.
The built-in Django development server is intended only for development purposes and is not suitable for production use. To deploy Django in a production environment, you should run it as a WSGI application using a web server such as Apache, Gunicorn, or uWSGI, or as an ASGI application using a server like Daphne or Uvicorn.
You can find detailed information about how to deploy Django with different web servers at:
https://docs.djangoproject.com/en/5.0/howto/deploym ent/wsgi/.
Project settings
Let’s open the settings.py file and examine the configuration of the project. Django includes several settings in this file, but these are only a portion of the available settings. You can view the complete list of Django settings along with their default values at:
Let’s review some key project settings:
DEBUG: This is a Boolean value that toggles the debug mode of the project. If set toTrue, Django will display detailed error pages when an uncaught exception occurs in your application. This is useful for development, as it provides valuable debugging information. However, when deploying your application to a production environment, you must set this toFalseto prevent exposing sensitive error details to users.Never deploy a site into production with DEBUG turned on because you
will expose sensitive project-related data.ALLOWED_HOSTS: This setting is not enforced while debug mode is active or when running tests. Once you switch to a production environment and setDEBUG = False, you must add your domain or host to this list in order for Django to serve your site. This is a security measure to prevent HTTP Host header attacks.INSTALLED_APPS: This setting specifies the list of Django applications that are active for your project. You will need to edit this list for most projects. By default, Django includes the following applications:django.contrib.admin: Provides an administration interface.django.contrib.auth: Handles user authentication and authorization.django.contrib.contenttypes: Supports content type framework.django.contrib.sessions: Manages user sessions.django.contrib.messages: Implements a messaging framework.django.contrib.staticfiles: Manages static assets like CSS, JavaScript, and images.
MIDDLEWARE: This is a list of middleware classes that Django will execute in order for each request and response. Middleware is used for processing requests, responses, sessions, authentication, and more.ROOT_URLCONF: This setting points to the Python module where the root URL patterns for your Django project are defined—typically set to'mysite.urls'.DATABASES: This is a dictionary containing the database configurations. There must always be adefaultdatabase defined. By default, Django uses SQLite3, which is ideal for development and testing purposes.LANGUAGE_CODE: Specifies the default language for your project. For example,'en-us'sets the language to U.S. English.USE_TZ: A Boolean setting that enables timezone-aware datetimes. When set toTrue, Django stores datetime values in UTC and translates them into the local timezone as needed. This is enabled by default when you create a new project using thestartprojectcommand.
Projects and Applications
Throughout this book, you will frequently encounter the terms project and application. In Django terminology:
- A project refers to the overall Django installation, which includes configuration settings and acts as the container for one or more applications.
- An application is a modular component that consists of models, views, templates, and URLs. Applications provide specific functionality and are designed to be reusable across different projects.
You can think of a project as your completeProjects and Applications website, while applications represent individual features within that website. For example, your site may contain applications such as a blog, wiki, or forum—each of which can be developed and reused independently in other Django projects.Projects and Applications
Throughout this book, you will frequently encounter the terms project and application. In Django terminology:
- A project refers to the overall Django installation, which includes configuration settings and acts as the container for one or more applications.
- An application is a modular component that consists of models, views, templates, and URLs. Applications provide specific functionality and are designed to be reusable across different projects.
You can think of a project as your complete website, while applications represent individual features within that website. For example, your site may contain applications such as a blog, wiki, or forum—each of which can be developed and reused independently in other Django projects.
Creating an application
Let’s create our first Django application, from scratch.
Run the following command in the shell prompt from the project’s root directory:
python manage.py startapp blogThis will create the basic structure of the application, which will look like this:
blog/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.pyThe following files are typically found in a Django application directory, such as a blog app. Each plays a specific role in how the application functions:
__init__.py: This is an empty file that indicates to Python that theblogdirectory should be treated as a Python package.admin.py: This file is used to register your models with the Django admin interface. It allows you to manage your application's data through a user-friendly backend. Using the admin interface is optional but highly useful during development and for administrative tasks.apps.py: This contains the main configuration for theblogapplication. It defines the application’s metadata and is automatically generated when you create a new app.migrations/: This directory stores database migration files for the application. Migrations are used by Django to track and apply changes made to the data models, allowing you to evolve your database schema over time without manual SQL intervention.synchronize the database accordingly. This directory contains an empty __init__.py file.models.py: This file defines the data models of your application. Data models are Python classes that map to database tables, enabling Django’s ORM (Object-Relational Mapping) features. While all Django applications include amodels.pyfile, it can be left empty if your app does not use any models.tests.py: This file is used for writing unit tests for your application. Writing tests is crucial for verifying that your application behaves as expected and for preventing regressions as you develop and maintain your code.views.py: This file contains the core logic of your application. Each view handles an incoming HTTP request, processes any necessary logic or data retrieval, and returns an HTTP response. Views are often connected to templates to render dynamic HTML pages.
With the application structure ready, we can start building the data models for the blog.
Road Map to become a django developer:
Upgrade Django project To New Version
If you want to quickly upgrade an existing Django project to the 5.0 release,you can use the django-upgrade tool. This package rewrites the files of your
project by applying fixers up to a target version. You can find instructions to use django-upgrade at
https://github.com/adamchainz/django-upgrade.
The django-upgrade tool is inspired by the pyupgrade package. You can use pyupgrade to automatically upgrade syntax for newer versions of Python.
You can find more information about pyupgrade at
https://github.com/asottile/pyupgrade
