Building a Web App with Python Django: A Step-by-Step Guide

Building a Web App with Python Django: A Step-by-Step Guide

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 skillset, 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:

  1. 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.
  2. 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.
  3. 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.
  4. 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:

  1. 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.
  2. View: represents the user interface of a web application. It's what users see and interact with in 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 Views in the Django Views Documentation.
  3. Template: consist 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

  1. Install Django within your virtual environment:

pip install Django        

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

pip install djangorestframework        

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

django-admin --version        

You should see the installed Django version.

2 . 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). For getting 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 webserver.

Let's create a project folder named test_project and change 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 bellow 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 they mange.py file was created in this case would be the test_project directory.

cd test_project

python manage.py runserver        

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

Let's stop the Development Server

Quit the server with on your keyboard:

 CONTROL-C        

3. Create an app in django

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

cd test_project        

now that we are inside the test_project folder let's create 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 include 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. In order 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 colde bellow. 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
from . 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 which 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 its 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 https://127.0.0.1:8000/ in your web browser. You should see a page similar to the following screenshot:



Conclusion

This article has provided a comprehensive guide on how to build a web app with Python Django. The official documentation for Django and DRF is an invaluable resource for in-depth learning and further exploration.

I encourage you to explore the Django Documentation and the Django REST Framework Documentation. They offer detailed guides, tutorials, and examples to help you become proficient in web development with these powerful tools.

Feel free to explore my example projects at my GitHub repo for the complete code of the example task manager. Building a web app is an exciting journey, and I hope this article serves as a useful starting point for your web development endeavors!

要查看或添加评论,请登录

Tamzidul Matin的更多文章

社区洞察

其他会员也浏览了