Home  >  Article  >  Backend Development  >  A complete tutorial on building web applications with Python and Django

A complete tutorial on building web applications with Python and Django

PHPz
PHPzOriginal
2023-06-23 11:22:311025browse

In the current digital era, web applications have become an essential part of business and personal projects. Python and Django are two of the most popular tools for building web applications. Python is an easy-to-learn programming language that has many advantages, including being easy to write, easy to maintain, and a high-performance programming language. Django is an open source web framework whose main purpose is to make it easier for developers to write high-quality and high-performance web applications. This article will introduce how to build web applications using Python and Django.

  1. Build a development environment

Before you start writing code, you need to make sure you have Python and Django installed on your computer. To set up a Python environment, please go to the official Python website to download the latest version of Python 3.x. To install Django, you need to run the following command:

pip install django
  1. Create Django project

After running the above command, you can create a basic Django by running the following command Project:

django-admin startproject myproject

Here myproject is the name of the project, you can name it yourself. This command will create a directory named myproject in the current directory and contain the following files and folders:

  • myproject/

    • manage.py
    • myproject/

      • __init__.py
      • settings.py
      • urls.py
      • wsgi.py

Among them, manage.py is a command line utility that provides you with some tools, such as running a development server, creating a database, etc. We'll learn more about it later. The settings.py file is a very important file in Django. It contains all the configuration information of the project, such as database settings, email settings, etc.

  1. Run the Django development server

After creating the project, you can use the following command to start the development server:

python manage.py runserver

This command will start Django Development server, and run on the default port (i.e. 8000). You can view your Django website by visiting http://localhost:8000.

  1. Create a Django application

Now that we have created a basic Django project and started the development server, we will create a Django application. An application is a relatively independent component in Django, which usually includes data models, views, and URLs. You can create a Django application with the following command:

python manage.py startapp myapp

This command will create a directory named myapp in the current directory and contain the following files and folders:

  • myapp/

    • __init__.py
    • admin.py
    • apps.py
    • models.py
    • tests.py
    • views.py

Among them, models.py is the data model definition of this application, and views.py is the view definition of this application , and admin.py is used to manage relevant information of this application.

  1. Define data model

Defining data model is an important part of Django application development, which allows you to create, read, update and delete data. In Django, data models can be defined through Python classes, and these classes will be converted into database tables. Specifically, you can define a User data model through the following code:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100)

In this example, we define a User class, which contains a CharField named name and an EmailField named email . For CharField and EmailField, you can set the maximum length by specifying the max_length parameter.

  1. Create data migration

After defining the data model, we need to perform data migration, that is, create the corresponding table in the database. You can generate data migration through the following command:

python manage.py makemigrations

This command will automatically generate a Python script named 0001_initial.py, which contains all data model changes. You can also apply data migration to the current database through the following command:

python manage.py migrate

This command will create the corresponding data table.

  1. Define the view

After defining the data model and completing the data migration, we need to define the view portion of the web application. Views are the main entry point for user interaction in a web application, converting requests and responses. In Django, we can define views through Python functions. Specifically, you can define a view through the following code:

from django.shortcuts import render
from django.http import HttpResponse
from myapp.models import User

def index(request):
    users = User.objects.all()
    context = {'users': users}
    return render(request, 'index.html', context)

In this example, we define a view named index, which passes a data object named users to the template. In this view, we retrieve all User objects from the database and return a template named index.html.

  1. Define URL routing

After defining the view, we need to forward the URL request to the corresponding view. In Django, we can accomplish this process through URL routing. Specifically, you can define a URL route through the following code:

from django.urls import path
from myapp.views import index

urlpatterns = [
    path('', index, name='index'),
]

In this example, we define a URL route named index, which forwards the root URL to the corresponding view function.

  1. 创建模板

在定义了视图和URL路由之后,我们需要为Web应用程序创建模板。模板是一种用于生成HTML页面的文件,它通常包含一些动态元素和数据。在Django中,你可以使用Django模板语言(DTL)来编写模板。具体而言,以下是一个名为index.html的模板的代码例子:

<!DOCTYPE html>
<html>
<head>
    <title>My Site</title>
</head>
<body>
    <h1>Users</h1>
    <ul>
        {% for user in users %}
            <li>{{ user.name }} ({{ user.email }})</li>
        {% endfor %}
    </ul>
</body>
</html>

在这个例子中,我们使用{% for %}标签来循环渲染User对象。

  1. 运行应用程序

在完成了所有的前置步骤之后,我们可以运行应用程序并查看效果。你可以通过以下命令来启动Django开发服务器:

python manage.py runserver

该命令会启动Django开发服务器,并运行在默认端口上(即8000)。你可以访问http://localhost:8000来查看你的Web应用程序。如果一切成功,你将会看到用户的列表。

通过以上10个步骤,你已经成功的创建了一个基础的Django应用程序。这个例子只是一个简单的入门指南,但它包含了很多Django的基础知识。如果你对Python和Django开发感兴趣,那么希望这篇文章可以帮助你开始你的Web应用程序之旅!

The above is the detailed content of A complete tutorial on building web applications with Python and Django. 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