Building web applications with Python and Django: a practical guide

王林
Release: 2023-06-22 17:51:30
Original
1380 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template