Home  >  Article  >  Backend Development  >  Getting Started with Django: A Procedural Python Web Framework Tutorial

Getting Started with Django: A Procedural Python Web Framework Tutorial

WBOY
WBOYOriginal
2023-06-22 10:06:40858browse

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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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
  1. 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.

  1. 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.

  1. 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>{{ blog.title }}</h1>
<p>{{ blog.body }}</p>
<p>Published on {{ blog.pub_date }}</p>
  1. 创建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。路径“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!

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