search
HomeBackend DevelopmentPython TutorialBuilding web applications with Python and Django: a practical guide
Building web applications with Python and Django: a practical guideJun 22, 2023 pm 05:51 PM
pythondjangoweb 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

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

django-admin --version

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

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

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

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

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)
  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

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

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'),
]

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')

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 id="Books">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 %}

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
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
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!