Embark on Django with Python: Your Journey to Building Web Applications

Sanat Ladkat
Python in Plain English
13 min readApr 7, 2024

--

So, you’re ready to dive into the world of web development, and Python Django is your chosen path. Get ready for an adventure filled with creativity, innovation, and the joy of building something incredible from scratch. Let’s explore Django together and discover how it can empower you to create web applications with ease and confidence.

Photo by Lala Azizli on Unsplash

What Does a Web Application Do?

Imagine a bustling city with various businesses, each serving a unique purpose. In this analogy, a web application is like a storefront in this city. It welcomes visitors (users) and provides them with products or services (content) based on their needs. Just like any business, a web application needs infrastructure, organization, and a clear understanding of its customers’ preferences to thrive.

Web Frameworks

Building a web application from scratch is like constructing a building without blueprints. It’s time-consuming, error-prone, and often leads to inconsistent results. That’s where web frameworks come in.

Think of a web framework as a set of blueprints and tools that streamline the development process. It provides a structured approach to building web applications, saving you time and effort along the way. Web frameworks are collections of tools and modules needed to perform standard tasks across every web application. They consist of standards required to build web applications, such as serving web pages, interacting with databases, and communicating with web hosts. These frameworks take care of repetitive tasks and provide a standardized starting point for developers’ projects.

Acting as 3rd party modules/libraries installed on the system, frameworks offer utility functionalities and methods to manage sessions, authentication, file uploads, and more. By handling these details, developers can focus on the core business logic of their websites, accelerating development and improving efficiency. Just like Django for Python, other popular programming languages also have their own web frameworks, such as Ruby on Rails for Ruby and CodeIgniter for PHP. These frameworks enable developers to quickly get started and concentrate on the unique aspects of their web applications, rather than spending time on standard tasks.

Meet Django: Your New Best Friend

Django is your trusty guide in the world of web development. It’s like having a seasoned mentor who knows all the tricks of the trade. Django provides a robust framework for building web applications in Python, offering everything you need to get started, from handling user authentication to interacting with databases.

Key Features of Django

  1. Built for Python 3.x: Django is tailor-made for the latest version of Python, ensuring compatibility and efficiency.
  2. Batteries Included: With Django, you don’t need to hunt for external libraries or tools. It comes with a comprehensive set of features out of the box, allowing you to focus on building your application.
  3. Real-World Applications: Django powers some of the most popular websites and web applications on the internet, proving its reliability and scalability in real-world scenarios.

Benefits of Django

  • Ease of Learning: Thanks to Python’s simplicity, Django is beginner-friendly, making it accessible to developers of all skill levels.
  • Open Source: Django is freely available, democratizing web development and empowering developers worldwide.
  • Rapid Development: By automating common tasks and providing clear guidelines, Django accelerates the development process, allowing you to bring your ideas to life quickly.
  • Scalability: Whether you’re building a small blog or a complex enterprise application, Django scales effortlessly to meet your needs.
  • Admin Interface: Django’s built-in admin interface simplifies site administration, allowing you to manage your application’s content with ease.

Prerequisites

Before diving into Django, it’s helpful to have a basic understanding of Python programming and web development concepts such as HTML, CSS, and JavaScript. However, don’t worry if you’re not an expert — Django is designed to be accessible to newcomers.

Setting Up Python and Understanding Virtual Environments

Before diving into Django, ensure you have Python installed on your system. If not, you can download and install it from the official Python website : https://www.python.org/downloads/
At the time of writing, the latest Python version available is 3.12.2, which is what we’ll be using for this guide.

Now, let’s delve into setting up Django on your system. But before we do that, let’s understand the importance of virtual environments.

What are Virtual Environments?

In virtual environments, packages and modules play a crucial role in isolating dependencies and facilitating project-specific configurations, ensuring clean and efficient development environments. They enable developers to manage dependencies effectively and maintain project-specific functionality without interference from external sources. Lets understand the in a better way with an analogy

Modules: Modules are like individual parts of furniture, such as the backrest, legs, and seat. Each module serves a specific function, just like each part of furniture has its purpose. Each module serves a specific purpose and can be used on its own. In Python, module is a file containing Python code that can define functions, classes, and variables. Modules help organize code into reusable units and are imported using the import statement.

Packages: When these modules are assembled together, they form a complete piece of furniture, akin to a chair or a table. This assembly of modules into a cohesive unit is similar to how packages in Python bring together related modules to provide broader functionality. Packages help organize modules into coherent groups, making it easier to manage and maintain your codebase. In Python package is a collection of Python modules grouped together. Packages allow for a hierarchical structuring of the module namespace using dot notation. They’re distributed as directories containing module files along with an __init__.py file.

Virtual Environment: Now, imagine a room furnished with different pieces of furniture like tables, chairs, TVs, and beds. This room represents a virtual environment in Python. It’s a contained space where various packages (furniture sets) coexist without interfering with each other. Each room (virtual environment) can have its own unique combination of furniture (packages), tailored to specific needs or projects, ensuring a clean and isolated development space.
In Python Virtual Environment is a self-contained directory tree containing a Python installation for a specific version, along with additional packages. Virtual environments isolate Python environments and dependencies for different projects, allowing different versions of packages to be used without conflicts. They’re created using the venv module (or virtualenv for older versions of Python), and packages are installed using pip.

Why Virtual Environments?

Simply put, a virtual environment is a tool that allows you to create isolated environments for your Python projects. Each virtual environment acts as a sandbox, with its own set of packages and dependencies. This means that you can install different versions of packages for different projects without worrying about conflicts.

In the world of Python development, managing dependencies can become a bit of a headache. Imagine you have multiple Python applications running on your system, each requiring different versions of the same packages. For instance, one application might need Django 1.5 and Python 2.3, while another requires Django 2 and Python 2.2. Managing these dependencies on a system-wide level could lead to conflicts and compatibility issues.

By using virtual environments, you can package each of these applications into separate environments, ensuring that they have their own space to run without interfering with each other. This isolation guarantees that each application can use the specific versions of packages it requires, allowing them to run smoothly without conflicts.

Now that we understand the importance of virtual environments, let’s dive into how to set them up on your system.

Setting Up a Virtual Environment for Django Development

Setting up a virtual environment is a crucial step in Django development. It allows you to create an isolated environment for your project, ensuring that you can manage dependencies and packages without affecting other projects on your system. Here’s how to set up a virtual environment for your Django project:

1. Create a New Directory: Start by creating a new directory for your Django project. Navigate to this directory using your terminal or command prompt.

mkdir django_projects
cd .\django_projects\

2. Create the Virtual Environment:

Syntax : python -m venv <environment_name>
Once you’re inside the directory, run the following command to create a virtual environment:

python -m venv django_web_app 

This command will create a new directory with the specified name (in this case, “django_web_app”) within your current directory.

3. Activate the Virtual Environment:
After creating the virtual environment, you need to activate it. Activating the virtual environment ensures that any commands you run are executed within this isolated environment.

Syntax: <directory_path>\Scripts\activate

D:\django_projects\django_web_app\Scripts\activate

Once activated, you’ll notice that your command prompt or terminal prompt changes to indicate that you’re now working within the virtual environment.
Remember, if you encounter any errors during activation, you can try appending “.bat” to the activation command on Windows. For example

D:\django_projects\django_web_app\Scripts\activate.bat

4. Start Developing:
With your virtual environment activated, you’re ready to start developing your Django project. Any packages you install or commands you run will now be isolated within this environment, ensuring that they don’t affect other projects on your system.

Installing Django

With your virtual environment activated, it’s time to install Django and start building your first project. Django can be installed using pip, Python’s package manager.

pip install Django

To validate if the framework has been installed properly type in following command in your terminal

django-admin --version

Django Project

A Django project is a collection of configurations, applications, and settings that define a web application or a website built using the Django web framework. In Django, a project acts as the top-level container for managing various components of a web application, such as URL routing, database configurations, and application-specific settings.
Think of this as laying the foundation for your web application — setting up the structure and configuration needed to bring your ideas to life.

django-admin startproject my_first_project

It’ll create a new directory with some prewritten files. Lets understand what does each of it mean.

‘manage.py’ is a command-line utility that lets you interact with your Django project. You can use it to run development servers, create new apps, and perform various other tasks.

‘init.py’ is an empty Python file that signifies that the current folder is a Python package. It should remain untouched.

‘settings.py’ acts as the backbone of your Django project, containing crucial settings such as security keys and debug mode, which is initially set to true for development purposes. Additionally, it lists all installed apps, including pre-installed ones like admin, auth, sessions, and messages. You can also add your custom apps as needed. Middleware settings manage features like security, sessions, and CSRF protection. Moreover, ‘settings.py’ configures templates and databases. Django ships with an inbuilt SQLite database, eliminating the need for manual configuration to get your app up and running. However, if you prefer a different database such as PostgreSQL or MongoDB, you can adjust these settings accordingly.

‘urls.py’ defines the URLs existing in our application. Each web application serves different URLs to its users. For instance, visiting the Amazon homepage triggers different actions than accessing a specific product page. These URLs serve as entry points for users to interact with the web application. While Django provides a predefined URL, ‘/admin’, you can define custom URLs as you build your application.

‘wsgi.py’ ensures that our application can interact with the web server when hosted. It stands for Web Server Gateway Interface and facilitates communication between the web server and our Django application. No changes are typically made to this file.

‘asgi.py’ stands for Asynchronous Server Gateway Interface and is gradually replacing WSGI. Although it functions similarly to WSGI, it offers enhanced capabilities. Like WSGI, ‘asgi.py’ facilitates communication between the web server and our Django application and usually requires no modifications.

Run Django Project

To run your Django project, navigate to the project folder in your terminal and execute the following command:

cd .\my_first_project\
python manage.py runserver

You may encounter an error about unapplied migrations, which can be ignored for now. We’ll address this later.
Your server is now up and running!
Copy the URL displayed in the terminal, which typically looks like ‘http://127.0.0.1:8000/', and paste it into your web browser. You’ll be greeted by a default page provided by Django, indicating that the installation was successful.

In the URL, ‘127.0.0.1’ represents the IP address of your local machine, while ‘8000’ is the port number. Since we haven’t deployed the application elsewhere, we access it using this combination of IP address and port number.

To stop the server, simply press ‘Ctrl+C’ in your terminal.

You can also specify a custom port number when running the server. For example:

python manage.py runserver 8001

This command will launch the server on port 8001, and you can access the default page at ‘http://127.0.0.1:8001/'.

Django App

What Exactly is a Django App? An app in Django encapsulates a specific functionality within a web application. Each app is designed to handle a discrete set of tasks, making the overall application more modular and easier to manage.

In a Django project, you can have multiple apps, each responsible for a distinct aspect of the application’s functionality. Let’s illustrate this with an example:

Imagine you’re developing an e-commerce website, and you’ve created a Django project named ‘ecommerce’. Within this project, you might have several apps such as ‘Orders’, ‘Authentication’, ‘Payments’, and ‘Carts’.

The ‘Orders’ app would handle tasks related to managing orders, such as accepting, updating, and processing orders. The ‘Authentication’ app would focus on user authentication processes like signing up, signing in, and password resets.

Similarly, the ‘Payments’ app would integrate with various payment gateways like Stripe and PayPal. Lastly, the ‘Carts’ app would manage all functionalities related to the shopping cart, including adding, deleting, and updating items.

While it’s not compulsory to split your project into multiple apps, doing so follows Django’s best practices and keeps your codebase organized and scalable.

Creating a Django App:

Syntax: python manage.py startapp <app_name>

For instance, if you want to create an app named ‘my_first_app’, you would run:

python manage.py startapp my_first_app

Executing this command generates a new directory with your specified app name within the project directory. It also creates a set of default files inside this directory:

  • __init__.py: This empty Python file signals that the directory is a Python package and should not be modified.
  • models.py: Here, you define the database structure, including the design, relationships, and attributes of your data models.
  • admin.py: This file is used to register Django models in the admin panel, allowing administrators to perform CRUD operations on the models.
  • tests.py: Use this file to write test cases for your web application, ensuring its reliability and robustness.
  • views.py: This file contains views that handle user interactions with the web application. Views are typically defined as classes and are crucial for rendering HTML templates and processing user requests.

Note: Don’t forget to create a urls.py file within the app directory manually. Similar to the main project's urls.py, this file defines all the URLs specific to the app.

With these files in place, your Django app is ready to be developed further!

How exactly does Django work?

Django operates on the principle of Model-View-Template (MVT), where each component plays a crucial role in the functioning of the framework.

Model: At the heart of Django lies the Model, which represents the logical data structure behind the entire application. Typically, these models are mapped to a database, with relational databases being the most common choice. However, Django offers flexibility in choosing any Database Management System (DBMS). The database serves as the repository for all application data, ensuring that information is persistently stored and accessible.

View: The View component encapsulates the business logic of the application. It acts as the engine driving the application’s functionality. When a user requests a page, Django creates an HTTP request object. This object is then passed to the appropriate view, which processes the request data, interacts with the models to retrieve or manipulate data, and prepares the necessary response. Essentially, the view orchestrates the flow of data between the user and the application.

Template: Templates are responsible for rendering HTML pages in the web browser. They handle the presentation layer of the application, incorporating HTML and CSS to create visually appealing and interactive user interfaces. Templates receive data from the views and use it to dynamically generate HTML content, which is then displayed to the user.

I sincerely hope this introductory guide has provided you with a solid foundation to kickstart your Django adventure. From understanding the fundamentals of web applications to setting up virtual environments and diving into Django projects, you’ve gained invaluable insights that will serve you well on your development journey.

Stay tuned for more articles where we delve into project-based Django tutorials, guiding you through real-world applications and empowering you to unleash your creativity. Together, we’ll continue to explore the endless possibilities Django offers, turning your ideas into fully functional web applications.

Keep experimenting, keep learning, and most importantly, keep building!

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--