search
HomeBackend DevelopmentPython TutorialBuilding 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
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
How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

How does the memory footprint of a list compare to the memory footprint of an array in Python?How does the memory footprint of a list compare to the memory footprint of an array in Python?May 02, 2025 am 12:08 AM

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

How do you handle environment-specific configurations when deploying executable Python scripts?How do you handle environment-specific configurations when deploying executable Python scripts?May 02, 2025 am 12:07 AM

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

How do you slice a Python array?How do you slice a Python array?May 01, 2025 am 12:18 AM

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Under what circumstances might lists perform better than arrays?Under what circumstances might lists perform better than arrays?May 01, 2025 am 12:06 AM

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

How can you convert a Python array to a Python list?How can you convert a Python array to a Python list?May 01, 2025 am 12:05 AM

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.

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

Video Face Swap

Video Face Swap

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

Hot Tools

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor