Home  >  Article  >  Backend Development  >  Getting Started with Django: A Complete Introduction to the Python Web Framework

Getting Started with Django: A Complete Introduction to the Python Web Framework

WBOY
WBOYOriginal
2023-06-22 10:20:083120browse

Django Getting Started Guide: A Complete Introduction to the Python Web Framework

In the world of web development, using frameworks for development is a common way. A framework is a code organization method that provides common structures, functions, and rules, allowing developers to quickly build fully functional, reliable, and easy-to-maintain Web applications. Python has many excellent web frameworks, and Django is currently the most popular one. This framework is widely used in the development of various web projects. This article will introduce the introductory knowledge of the Django framework and help beginners get started quickly.

  1. What is Django

Django is a web application framework written in Python. Its goal is to make the process of developing high-quality web applications as easy, fast, and fun as possible. Django follows the MVC (Model-View-Controller) design pattern and provides many powerful tools and functions to help developers build efficient web applications.

  1. Advantages of the Django framework

The Django framework has the following advantages:

  • Highly modular: The Django framework is based on the design principle of loose coupling. With a highly modular architecture, different modules can be written, tested and debugged independently, improving developer efficiency.
  • Easy to extend: The Django framework provides a rich set of plug-ins and modules that can be easily extended and customized.
  • High security: The Django framework has many built-in security features, such as XSS (cross-site scripting) protection, CSRF (cross-site request forgery) protection, password hashing, etc., allowing developers to build a secure Web app.
  • ORM (Object Relational Mapping) support: The Django framework has a built-in ORM system, which can facilitate database operations.
  • Comes with a backend management system: The Django framework comes with a rich backend management system that allows developers to easily develop content management systems (CMS).
  1. Django installation and configuration

Before you start using Django, you must first install Python. The Django framework can be installed through the command line, using the following command:

pip install Django

After the installation is completed, you can use the following command to verify whether the installation is successful:

django-admin version

If the version number is output, the installation is successful.

  1. Basic components of Django Web framework

Django’s components can be divided into the following parts:

  • Model layer: This is the M layer in Django's MVC, responsible for the storage and operation of data.
  • View layer (View): This is the V layer in Django's MVC, responsible for processing HTTP requests and returning HTTP responses.
  • Template layer (Template): This is the C layer in Django's MVC, responsible for rendering data and generating HTML responses.
  • URL routing (URLconf): Responsible for distributing HTTP requests to the corresponding view functions.
  1. Creation of Django project

To use Django to create a web application, you need to create a Django project first. Use the following command to create a Django project named mysite:

django-admin startproject mysite

After the command is executed, a directory named mysite will be created in the current directory, which contains a file named manage.py and a A subdirectory named mysite. manage.py is a Django command line tool used to manage various operations of Django projects.

  1. Creation of Django applications

In a Django project, each function or business logic can be regarded as an application. Django supports the creation of multiple applications and Combined into a complete web application, execute the following command in the mysite directory to create an application named myapp:

python manage.py startapp myapp

After executing the command, a subdirectory named myapp will be created in the mysite directory , which contains the application's code and related configuration files.

  1. Writing view functions for Django applications

View functions are a key component of Django applications. They handle HTTP requests and return HTTP responses. View functions can be written in the views.py file in the myapp directory. For example, write a view function that returns the "Hello World!" string in this file:

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello World!")

In the above code, we use the HttpResponse class, which is used to generate HTTP responses. To associate this view function with a URL, the following configuration is required:

from django.urls import path
from . import views

urlpatterns = [
    path('hello/', views.hello, name='hello'),
]

The above code uses the path function to associate the /hello/ URL to the view function named hello.

  1. Django Web Framework Template

The Django framework supports templates (Template) to separate data from views, making the code clearer and easier to maintain. Templates are HTML files that can contain dynamic data, loops, conditional statements, etc.

Using Django templates requires the following operations:

  • Create a subdirectory named templates in the myapp directory.
  • Create an HTML template file named hello.html in this directory:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
    <h1>{{msg}}</h1>
</body>
</html>

In the above code, double brackets "{{}}" syntax is used to represent the template A variable in that will be replaced when rendering the template.

Write a view function and pass data to the template for rendering:

from django.shortcuts import render

def hello(request):
    data = {'msg': 'Hello World!'}
    return render(request, 'hello.html', data)

Use the render function for template rendering and pass the data dictionary as a parameter to the template.

  1. Django数据库操作

在Django项目中,Django提供了一个内置的ORM框架,它方便开发者进行数据库操作。在mysite目录下的settings.py文件中可以进行数据库配置,该文件包含了DATABASES配置节点,该节点用于配置数据库连接相关信息。

在myapp目录下的models.py文件中可以定义数据库模型,例如定义一个名为Person的数据模型类:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

以上代码中,使用了CharField和IntegerField数据类型来定义模型的字段。使用以下命令可以在数据库中创建该数据模型对应的表:

python manage.py makemigrations
python manage.py migrate

以上命令会根据models.py文件中的定义,在数据库中创建相应的数据表。

  1. Django应用程序的注册

在mysite目录下的settings.py文件中可以进行应用程序注册,将创建的应用程序添加到INSTALLED_APPS配置节点中:

INSTALLED_APPS = [
    'myapp',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

添加应用程序到INSTALLED_APPS节点后,需要在myapp目录下创建名为admin.py的文件,用于创建管理界面。

  1. Django自带后台管理系统

Django提供了一个功能强大的后台管理系统,该系统可以自动根据模型创建对应的管理界面。在myapp目录下的admin.py文件中可以注册模型以创建管理界面,例如:

from django.contrib import admin
from .models import Person

admin.site.register(Person)

以上代码中,使用了register函数来注册Person数据模型,该函数会自动创建对应的管理界面。

  1. Django应用程序的启动

在编辑好Django应用程序之后,通过以下命令即可启动该应用程序:

python manage.py runserver

命令执行后,Django应用程序会运行在本地服务器上,可以在浏览器中访问http://localhost:8000/hello/ URL查看效果。

  1. 结语

Django框架是一个完整的Python Web框架,拥有强大的工具和功能来帮助开发者构建高效、稳定的Web应用程序。本文介绍了Django框架的基础知识,涉及了Django项目的创建、模型定义、视图函数编写、模板使用和后台管理系统等方面。通过本文的学习,读者可以快速入门并掌握Django框架的基础知识,进一步深入学习和应用该框架。

The above is the detailed content of Getting Started with Django: A Complete Introduction to the Python Web Framework. 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