Home > Article > Backend Development > Getting Started with Django: A Procedural Python Web Framework Tutorial
Django is an open source Python web framework that is highly extensible and flexible. It adopts the "Model-View-Controller (MVC)" design pattern to make the development of Web applications fast and efficient. This article will provide a detailed introduction to the basic knowledge of Django, importing and installing Django, creating a database, model building and view creation to help beginners master Django.
1. Basic knowledge of Django
The main components of Django include: URL scheduler, template engine, views and database access layer, etc. Django supports multiple databases and uses ORM (Object Relational Mapping) tools to provide object representation and access databases. It supports multiple web servers at the same time, such as Apache, Nginx, etc. Django also provides a wealth of functions and components, such as management backend, form processing, internationalization, security and authentication, etc.
2. Import and install Django
Before installing Django, you need to confirm that Python has been installed successfully. There are two ways to install Django: one is to use the pip command (recommended), and the other is to download and install manually. Here we introduce the pip installation method.
pip install virtualenv
Next, create a new virtual environment using the following command.
virtualenv djangoenv
In this example, the name of the virtual environment is djangoenv.
pip install Django
This command will automatically download the latest version and install it in the site-packages directory of the virtual environment.
3. Create a database
Django supports multiple database systems, such as MySQL, PostgreSQL, etc. In this article, we will use the default SQLite database. SQLite is already installed after installing Python.
django-admin startproject mysite
In this example, the name of the project is mysite.
cd mysite python manage.py startapp blog
This command will create a directory named blog in the root directory of the project.
Note: This command must be run in the root directory of the project.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
This setting sets the database type to SQLite, And name the database file db.sqlite3. The DATABASES setting also supports other relational databases such as MySQL and PostgreSQL.
python manage.py makemigrations python manage.py migrate
This command will create a database file and create the necessary tables to manage the database model for all applications used by Django.
4. Model Construction
The model is a key part of mapping data to the database. In order to use the model, we need to define a Python class that will be used to define the table in the database. Django's ORM supports many different database types, and for convenience, we will use the SQLite database in this article.
from django.db import models class Blog(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') body = models.TextField() def __str__(self): return self.title
python manage.py makemigrations blog python manage.py migrate
This command will create a new table in the database, which will contain the data model we have defined.
5. View creation
The view is the part where the user interacts with the application. A view is a set of functions that get data from the model and render the results to the user's browser. In Django, all views must return an HTTP response object. Django also provides some commonly used view types.
from django.shortcuts import render from django.http import HttpResponse from .models import Blog def index(request): latest_blog_list = Blog.objects.order_by('-pub_date')[:5] context = {'latest_blog_list': latest_blog_list} return render(request, 'blog/index.html', context) def detail(request, blog_id): blog = Blog.objects.get(pk=blog_id) return render(request, 'blog/detail.html', {'blog': blog})
Two views are defined here: index and detail. The index view will get the latest 5 blog posts and render them into the HTML template one by one. The detail view will take the details of a blog post and render them into an HTML template.
index.html
{% if latest_blog_list %} <ul> {% for blog in latest_blog_list %} <li><a href="{% url 'blog:detail' blog.id %}">{{ blog.title }}</a></li> {% endfor %} </ul> {% else %} <p>No blogs are available.</p> {% endif %}
detail.html
<h1>{{ blog.title }}</h1> <p>{{ blog.body }}</p> <p>Published on {{ blog.pub_date }}</p>
from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.index, name='index'), path('<int:blog_id>/', views.detail, name='detail'), ]
在这个文件中,我们使用URL配置了两个视图函数:index和detail。路径“283b0284c70ce5b35f6a4cddbe3f14e7/”定义了一个变量blog_id,并将其传递给detail视图函数。
六、启动服务器
现在我们已经定义了我们的Django应用程序,我们可以启动服务器并测试它是否正常工作了。在命令行中输入以下命令。
python manage.py runserver
如果一切正常,您将看到以下输出。
Performing system checks... System check identified no issues (0 silenced). September 18, 2021 - 18:13:35 Django version 3.2, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK.
现在您可以打开浏览器,并输入地址http://127.0.0.1:8000/blog/来访问您的Django网站。
七、总结
本文提供了一个Django入门指南,介绍了Django的基础知识,导入和安装Django,创建数据库,模型构建和视图创建等方面的内容。希望本文能够帮助初学者更好地理解Django,并在他们的Web开发项目中使用它。在Web开发的繁荣时代,Django无疑是一个强大的工具。
The above is the detailed content of Getting Started with Django: A Procedural Python Web Framework Tutorial. For more information, please follow other related articles on the PHP Chinese website!