Building Web Applications with Django: A Python Framework

April 20, 2024
Building Web Applications with Django: A Python Framework

In the world of web development, Python Django and Django REST framework (DRF) have become powerful tools for creating robust and scalable web applications. Whether you’re a beginner looking to start your web development journey or an experienced developer seeking to enhance your skill set, this article will guide you through the process of building a web app using these technologies.

Why Django for Web Development?

When it comes to web development, choosing the right framework can significantly impact your project’s success. Django, a high-level Python web framework, is renowned for its efficiency, security, and ease of use. Here are a few reasons why Django is a popular choice among developers:

Rapid Development: Django’s “batteries-included” philosophy means it comes with a wide range of built-in features, including an ORM (Object-Relational Mapping), authentication, and admin panel. This allows developers to build web applications quickly, reducing development time and effort.

Rapid Development: Django “batteries-included” philosophy means it comes with a wide range of built-in features, including 

Security: Django takes web security seriously. It includes features like protection against common security vulnerabilities, such as SQL injection, XSS (Cross-Site Scripting), and CSRF (Cross-Site Request Forgery), by default. With Django, you can focus on your application’s logic while the framework handles security.

Scalability: Django is designed to handle projects of all sizes, from small applications to large-scale websites with high traffic. Its modular architecture allows you to add and remove components as your project evolves, ensuring scalability and maintainability.

Community and Documentation: Django has a thriving community of developers and a wealth of resources, including extensive documentation. You can easily find tutorials, packages, and solutions to common problems, making it a developer-friendly choice.

Django is based on the MVT (Model-View-Template) architecture, which is a software design pattern used for developing web applications. MVT consists of three main components:

Model: is responsible for managing and maintaining data. It acts as the interface to your data storage, which is typically a relational database like MySQL or PostgreSQL.Functionality: Models define the structure of your database tables, including fields and relationships between tables. They provide an abstraction layer for data manipulation.

Use: Models allow you to create, read, update, and delete data in the database. They encapsulate the logic for database interactions. You can find more information about Django Models in the Django Models Documentation.

View: represents the user interface of a web application. It’s what users see and interact with within their web browsers. Views are typically composed of HTML, CSS, JavaScript, and Jinja templates. 

Functionality: Views are responsible for rendering the HTML pages that users view. They combine templates (which define the structure of the page) with dynamic content.

Use: Views handle user requests, interact with models to fetch or update data, and then render the appropriate HTML response. They control the application’s logic. Learn more about Django 

Advantages of using Django for building Web Applications

Hiring Django developers for building Web Applications offers the following advantages:

Enhanced security: This is one of the most amazing features of Django. You don’t have to implement security features manually while using the Django platform. Security patches are deployed frequently to meet the latest security standards.

Faster Development: Django is designed for faster development it reduces the development time to a great extent. Further, it makes the web development process affordable. It is simply the best platform for the on-time delivery of web applications.

Highly scalable: Django is known for its high scalability, apps built on it can easily handle high traffic. No matter how heavy the network demand is apps built on Django will ensure to meet that flawlessly.

Large community support: Django has huge community support which is an asset for all Django developers. If you face any issues during the web development process you can ask the Django community for help and enhance your development process.

Views in the Django Views Documentation.

Template: consists of static HTML parts and special syntax that describe how dynamic content is inserted into the HTML output. They define the structure and layout of web pages. 

Functionality: Templates provide a way to separate the presentation layer from the application logic. They include placeholders for dynamic data that will be inserted during rendering. 

Use: Templates are used by views to generate HTML responses. They allow you to create reusable layouts and components for your web pages. Explore Django Templates in the Django Templates Documentation. With these fundamentals in mind, let’s dive into the process of building a web app using Django.

Step 1: Django Installation

Install Django within your virtual environment:

While our virtual environment is activated, install any additional packages you need for your project. For example, to install the Django REST framework:

pip install djangorestframework

Verify Django Installation: After installation, we can verify that Django is installed by running:

Django-admin –version

You should see the installed Django version.

Create a Django Project

Project Structure

A Django Project when initialized contains basic files by default such as manage.py, view.py, urls.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the folder ( project folder ) there will be the following files- 

manage.py- This file is used to interact with your project via the command line(start the server, sync the database… etc). To get the full list of commands that can be executed by manage.py, type the help command

python manage.py help 

init.py: this is a Python package. It is invoked when the package or a module in the package is imported. We usually use this to execute package initialization code, for example for the initialization of package-level data.

setting.py: As the name indicates it contains all the website settings. In this file, we register any applications we create, the location of our static files, database configuration details, etc.

urls.py – In this file, we store all links of the project and functions to call.

wsgi.py – This file is used in deploying the project in WSGI. It is used to help your Django application communicate with the web server.

Let’s create a project folder named test_project and change the directory into it. 

mkdir test_project

cd test_project

Now let’s create a Django project named config in our current directory 

django-admin startproject config. 

This should create a config folder containing the following files below along with a mange.py file 

in our test_project folder. 

Let’s Run the Development Server

Make sure you are in the directory where the mange.py file was created in this case would be the test_project directory. 

cd test_project

python manage.py runserver

Let’s stop the Development Server

Quit the server with on your keyboard: 

 CONTROL-C

Create an app in Django

Before creating the app, let’s make sure we change the directory into our test_project folder

cd test_project

now that we are inside the test_project folder let’s create a Django app named test_app

django-admin startapp test_app

This will create a test_app directory and a db.sqlite3 file along with models and views. 

Add your app definition in settings.py 

Django provides some pre-installed apps for users. To see pre-installed apps, navigate to test_project –> test_app –> settings.py. In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer’s comfort. 

So, we have finally created an app but to render the app using URLs we need to include the app in our main project so that URLs redirected to that app can be rendered. Let us explore it.  Go to test_project ->config-> urls.py and add below code.

from django.urls import include

urlpatterns = [

    path(“admin/”, admin.site.urls),

    # Enter the app name in following syntax 

    path(”, include(“test_app.urls”)),

]

With this included function added now, we can use the default MVT model to create URLs, models, views, etc. in our test_app and they will be automatically included in our main test_project/config folder. The main feature of Django Apps is independence, every app (test_app) functions as an independent unit in supporting the main project (config). 

However, the urls.py file in the config folder will not be able to access the test_app’s urls. For our Django Web app to run properly we have to create another urls.py file in the test__app’s directory and include the following code below. This will invoke the function we will create which is defined in the views.py file so that it can be seen properly in the Web browser. 

from Django.urls import path

 

#import the views.py file into this code

. import views

urlpatterns=[

   path(”,views.index)

]

Now let’s create a function called index in the views.py file in our test_app folder.

from django.shortcuts import render

#import the django HttpResponse module

from django.http import HttpResponse

# Create your views here.

# define a function for our view with the HttpResponse function

def index(request):

   return HttpResponse(“Hello World”)

This code will call or invoke the function that is defined in the views.py file so that it can be seen properly in the Web browser.

Go to the settings.py file which is in the project directory in our case it’s the config folder, and change the value of ROOT_URLCONF from ‘project.urls’ (config) to ‘app.urls’ (test_app)

 

Let’s run the server again 

python manage.py runserver

Go to http://127.0.0.1:8000/ in your web browser. You should see a page similar to the following screenshot: 

Conclusion

This article offers a detailed guide on creating a web app using Python Django. The official Django and DRF documentation is an invaluable resource for deepening your understanding and exploring further.

I recommend delving into the Django Documentation and the Django REST Framework Documentation. They provide thorough guides, tutorials, and examples to enhance your proficiency in web development with these robust tools.

 

Feel free to check out my example projects on my GitHub repository for the complete code of the example task manager. Building a web app is an exciting journey, and I trust this article will serve as a valuable starting point for your web development pursuits!