Home Backend Development Python Tutorial Building web applications with Python and Django: a practical guide

Building web applications with Python and Django: a practical guide

Jun 22, 2023 pm 05:51 PM
python django web application.

Python is a popular programming language with the advantages of being easy to learn, highly readable and widely used. Python is widely used in web development, data science, machine learning and other fields. Among them, Django is an advanced web framework developed based on Python language and is an important tool for web application development.

Django is characterized by the advantages of being easy to learn, easy to maintain, following the MVC pattern, and comes with its own ORM, so it is popular among developers. This article will provide a practical guide to building web applications using Python and Django.

  1. Install Python and Django

First, we need to install Python and Django. You can download the latest Python installation package from the official Python website (www.python.org). After installation, you can enter python in the command line to check whether Python is installed correctly.

Installing Django can be installed through the pip package manager. Open the command line window and enter the following command:

pip install django
Copy after login

After the installation is completed, you can check whether Django is installed correctly through the following command:

django-admin --version
Copy after login

If the Django version number is returned, the installation is successful.

  1. Create a Django project

In the command line, enter the directory where you want to store the Django project, and then enter the following command:

django-admin startproject myproject
Copy after login

This command will create a The Django project named "myproject" has the following project directory structure:

myproject/
    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        wsgi.py
Copy after login

Among them, manage.py is a script file used to execute Django tasks on the command line; settings.py contains the project settings; urls. py contains the project's URL pattern; wsgi.py specifies which Python application the web server forwards requests to.

  1. Create a Django application

In a Django project, an application refers to a component that combines a web application with specific business logic. We can create an application in the created Django project using the following command:

python manage.py startapp myapp
Copy after login

This command will create an application named "myapp" in the "myproject" directory in the Django project, application directory The structure is as follows:

myapp/
    __init__.py
    admin.py
    apps.py
    models.py
    tests.py
    views.py
Copy after login

Among them, models.py contains the database model definition of the application; views.py contains the request processing function; admin.py is used to manage the background; tests.py contains the test code of the application.

  1. Writing Django models

Django’s ORM is a tool that maps Python classes to database tables. We can define the application’s model by editing the models.py file. .

For example, we create a model named "Book", which contains the following attributes:

  • title: String type, the maximum length is 200 characters
  • author (author): String type, maximum length is 50 characters
  • pub_date (publication date): Date type
  • price (price): decimal type , the maximum value is 9999.99, and the decimal place is 2 places

The code is as follows:

from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=50)
    pub_date = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2, max_value=9999.99)
Copy after login
  1. Create database table

In Django, database Tables are created automatically from the model. We can use the following command to create the model into the database:

python manage.py makemigrations myapp
Copy after login

This command will create a database migration file describing how to map the model to a database table. We can use the following command to apply migration to the database:

python manage.py migrate
Copy after login

This command will create the table into the database according to the instructions in the migration file.

  1. Writing Views

In Django, views are request processing functions, responsible for processing requests initiated by users and generating response content. Before writing the view, we need to configure the URL pattern to associate the request with the view. We can edit the urls.py file and add the following code:

from django.urls import path
from . import views

urlpatterns = [
    path('books/', views.book_list, name='book_list'),
    path('books/new', views.book_new, name='book_new'),
    path('books/<int:pk>/edit/', views.book_edit, name='book_edit'),
    path('books/<int:pk>/delete/', views.book_delete, name='book_delete'),
]
Copy after login

This code snippet defines 4 URL patterns, which are associated with 4 views. Among them, the first parameter of the path function specifies the URL, the second parameter specifies the view function, and the third parameter is the name of the template engine when rendering the view into HTML.

In the views.py file, we can define the request processing function, for example:

from django.shortcuts import render, get_object_or_404
from .models import Book
from .forms import BookForm

def book_list(request):
    books = Book.objects.all()
    return render(request, 'book_list.html', {'books': books})

def book_new(request):
    if request.method == "POST":
        form = BookForm(request.POST)
        if form.is_valid():
            book = form.save(commit=False)
            book.save()
            return redirect('book_list')
    else:
        form = BookForm()
    return render(request, 'book_edit.html', {'form': form})

def book_edit(request, pk):
    book = get_object_or_404(Book, pk=pk)
    if request.method == "POST":
        form = BookForm(request.POST, instance=book)
        if form.is_valid():
            book = form.save(commit=False)
            book.save()
            return redirect('book_list')
    else:
        form = BookForm(instance=book)
    return render(request, 'book_edit.html', {'form': form})

def book_delete(request, pk):
    book = get_object_or_404(Book, pk=pk)
    book.delete()
    return redirect('book_list')
Copy after login

Among them, the book_list function is used to return a list of all books; the book_new function is used to create a new book; book_edit The function is used to edit existing books; the book_delete function is used to delete books.

  1. Writing HTML templates

In Django, we can use the template engine to render the view function into an HTML page, thereby presenting a visual web interface to the user. We can create an HTML template file in the templates directory, such as book_list.html.

The code is as follows:

{% extends 'base.html' %}

{% block content %}
  <h1>Books</h1>
  <a href="{% url 'book_new' %}">New book</a>
  <table>
    <thead>
      <tr>
        <th>Title</th>
        <th>Author</th>
        <th>Pub date</th>
        <th>Price</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {% for book in books %}
        <tr>
          <td>{{ book.title }}</td>
          <td>{{ book.author }}</td>
          <td>{{ book.pub_date }}</td>
          <td>{{ book.price }}</td>
          <td>
            <a href="{% url 'book_edit' book.id %}">Edit</a>
            <a href="{% url 'book_delete' book.id %}">Delete</a>
          </td>
        </tr>
      {% endfor %}
    </tbody>
  </table>
{% endblock %}
Copy after login

Among them, {% extends 'base.html' %} specifies that this template inherits from the base.html template; {% block content %} to {% endblock %} Specifies that the main content in this template is the content contained within it.

We run the Django server and open localhost:8000/books/ in the browser to view the list of all books.

Through this simple example, we learned how to use Python and Django to build web applications, and involved basic operations, including installing Python and Django, creating Django projects and applications, and writing Django models and views and templates. Hope this guide helps you build your own web application.

The above is the detailed content of Building web applications with Python and Django: a practical guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

See all articles