


Building web applications with Python and Django: a practical guide
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.
- 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.
- 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.
- 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.
- 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)
- 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.
- 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.
- 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!

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

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

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

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

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor
