


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.
- Create a virtual environment
Virtual environments can help us manage different dependent libraries in different projects. First, we need to install a module called virtualenv. Enter the following command on the command line to install (provided pip is already installed).
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.
- Installing Django
In a virtual environment, use the following command to install Django.
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.
- Create Project
Use the following command to create a new Django project.
django-admin startproject mysite
In this example, the name of the project is mysite.
- Create an application
Django applications are composed of models, views and templates. Here, we will create an application called blog.
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.
- Configuring the database
Open the mysite/settings.py file and set DATABASES as follows:
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.
- Run Migrations
Django uses migrations to manage synchronization of data models and databases. Run the initial migration using the following command.
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.
- Create model
Create a Python class and define its properties. This class will serve as the data model for the application.
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
- Model migration
After we create the model, we need to run the following command to migrate the model to the database.
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.
- Create views
Create the following views in the file blog/views.py.
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.
- Create Template
In the view we defined, we used two HTML templates: index.html and detail.html. Create a directory named "templates" in the root directory of the blog application, and create a directory named "blog" under the templates directory. Create two HTML files named "index.html" and "detail.html" in the blog directory.
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 id="blog-title">{{ blog.title }}</h1> <p>{{ blog.body }}</p> <p>Published on {{ blog.pub_date }}</p>
- 创建URL
最后,我们要将视图与URL相关联。在blog应用程序的根目录下创建一个名为“urls.py”的文件,并添加以下内容。
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。路径“
六、启动服务器
现在我们已经定义了我们的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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.