[Master Python in 100 days] Day50: Python Web Programming_Django framework from installation to use

Table of contents

1 Install Django web framework

2 Create a Django project

3 Data model

3.1 Define the data model in the application’s models.py file

3.2 Create the migration file of the model and apply it

3.2.1 Query model objects:

3.2.2 Create a new model object:

3.2.3 Update model object:

3.2.4 Delete model objects:

3.2.5 Render model objects in templates:

4 Management background

4.1 Register the model in the application’s admin.py file

4.2 Create an administrator user

4.4 Start the development server and access the management background

4.5 Use the created administrator account to log in to the management backend

5 Routing and Views

5.1 Create the urls.py file of the application:

5.2 Define URL mapping in the application's urls.py file:

5.3 Configure project-level URL mapping:

5.4 Create view function:

5.5 Test routing:

6 Django templates

6.1 Create template file

6.2 Passing data to templates

6.3 Using template tags

 6.4 Template inheritance

 6.5 Template filters

1 Install Django web framework

   (1) Open the terminal or command prompt.

   (2) Use pipthe tool to install Django. pipIt is a package management tool for Python and is usually included when Python is installed. You can install Django using the following command

pip install Django

 This will download and install the Django framework and its dependencies.

  (3) Verify installation

Enter the following command in the terminal to verify that Django was installed successfully:

django-admin --version

 If you see the version number of Django, then Django has been successfully installed.

2 Create a Django project

To create a Django project, you can follow these steps:

2.1 Open the terminal or command prompt

2.2 Use the following command to create a new Django project

Replace "myproject" with your desired project name:

django-admin startproject myproject

This will create a new project directory called "myproject" under the current directory and contain the basic structure of the Django project within it.

2.3 Enter the project directory

Use cdthe command to enter the project directory:

cd myproject

2.4 Create a Django application

        Creating an application in a Django project is an important step because it allows you to divide the project into modules, each responsible for a different functionality. A Django project can contain one or more applications, which are units of code organization.

        Here are the steps to create an application in a Django project: Create a new application with the following command, replacing "myapp" with your application name:

python manage.py startapp myapp

 This will create a new application directory named "myapp" in the project directory. The directory structure is as follows:

Among them, under the myproject project file, the functions of each file are:

Under the application myapp folder:

在 myapp/models.py 文件中定义你的数据模型。这些模型将用于描述应用程序的数据结构。

在 myapp/views.py 文件中创建视图,这些视图定义了应用程序的业务逻辑。

在 myapp/urls.py 文件中配置 URL 映射,将 URL 与视图关联起来。

        If desired, the Django admin interface can myapp/admin.pybe configured in the file to be able to manage the application's data.

        Write test cases in myapp/tests.pythe file to ensure that the functionality of the application works properly.

        Finally, add your application to the project's configuration. Open the file in the project directory settings.pyand INSTALLED_APPSadd your application to the list:

# settings.py

INSTALLED_APPS = [
    # ...
    'myapp',
    # ...
]

as follows 

 2.5 Configure database

        Open the file in the project directory settings.pyand configure the database connection. By default, Django uses a SQLite database, but you can change to a different database backend if needed. The following is an example of a typical settings.pydatabase configuration in :

# settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',  # 数据库引擎
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),  # 数据库文件的绝对路径
    }
}

2.6 Migrate database

Run the following command to create the database table:

python manage.py makemigrations
python manage.py migrate

as follows:

2.7 Running the development server

Start the Django development server using the following command:

python manage.py runserver

     You'll see output from the server starting, which includes the URL to access your project, usually http://127.0.0.1:8000/. Open this URL, and you will see Django's welcome page as follows, indicating that your project has been successfully created.


        You've now created a Django project and can start developing your application within it. Add views, models, templates, and URL mappings to your project to build your web application. Check out the official Django documentation for an in-depth look at how to use Django: https://docs.djangoproject.com/en/stable/ icon-default.png?t=N7T8https://docs.djangoproject.com/en/stable/

3 Data model

        In Django, the data model is the key part used to define the data structure of the application. A model defines the structure of a database table, including field types, validation rules, and relationships. The following are the basic steps to create and use a data model:

models.py3.1 Define the data model in the application's file

        Each data model is a Python class, usually inherited from the django.db.models.Modelclass.

from django.db import models

class MyModel(models.Model):
    # 定义模型字段
    field1 = models.CharField(max_length=100)
    field2 = models.IntegerField()
    field3 = models.DateTimeField(auto_now_add=True)
    # ...其他字段...

    def __str__(self):
        return self.field1  # 可选,用于在管理界面中显示模型对象的字符串表示

        In the above example, we defined a MyModeldata model named , which contains three fields: field1, field2and field3. You can add more fields as needed and use different field types (for example, character, integer, datetime, etc.).

 Common field types in Django data models

3.2 Create the migration file of the model and apply it

        The migration file for the model is created to ensure that the database is synchronized and consistent with the data model in Django. The migration file contains the creation, modification, and deletion operations of the database table, which are makemigrationsautomatically generated by Django when executing the command.

The main reasons include:

  1. Version control database structure: The migration file records the evolution history of the database structure, enabling multiple developers or team members to collaborate on development and ensure that each database is in the same state. This is especially important for multi-environment deployments such as development, test, and production environments.

  2. Protecting Data Integrity: Migration files ensure that existing data will not be destroyed when the data model is modified. Django generates SQL statements to perform database updates to accommodate model changes.

  3. Ease of upgrade and maintenance: As the application evolves, the data model may require multiple changes. Migration files allow you to track these changes, making upgrades and maintenance easier and more manageable.

  4. Automated database management: Django provides a way to automatically manage the database structure. Developers only need to define the data model instead of manually writing complex database table creation and modification scripts.

        In short, creating a model migration file is a good development practice that can ensure that the database and the application's data model are kept in sync, improving the efficiency of development and maintenance while ensuring data integrity and version control. This is one of the core functions of Django's database migration system. 

Run the following command:

python manage.py makemigrations
python manage.py migrate

 This will create a data table corresponding to the model in the database.

Use models in your application. You can query, create, update, and delete model objects in views, and render them in templates. Here are some common example operations:

3.2.1 Query model objects:

my_objects = MyModel.objects.all()  # 获取所有 MyModel 对象
my_object = MyModel.objects.get(id=1)  # 获取特定的 MyModel 对象

3.2.2 Create a new model object:

new_object = MyModel(field1='Value 1', field2=42)
new_object.save()

3.2.3 Update model object:

my_object = MyModel.objects.get(id=1)
my_object.field1 = 'New Value'
my_object.save()

3.2.4 Delete model objects:

my_object = MyModel.objects.get(id=1)
my_object.delete()

3.2.5 Render model objects in templates:

        In Django templates, you can use template tags to render data from model objects. For example, to display the values ​​of field1and field2, use the following code:

<p>{
   
   { my_object.field1 }}</p>
<p>{
   
   { my_object.field2 }}</p>

        These are the basic steps in creating and using a data model. You can define different data models according to your application needs and use them in views and templates to manipulate and present data. 

4 Management background

        Django provides a built-in admin backend that allows you to easily manage your application's data. To use Django to manage the background, you need to perform the following configuration and steps:

admin.py4.1 Registering the model in the application's file

        Open the application's admin.pyfile and register the models to be managed in the admin backend with admin.site.register. For example 

from django.contrib import admin
from .models import MyModel

admin.site.register(MyModel)

 This will make MyModelthe model visible in the admin.

4.2 Create an administrator user

Run the following command in the terminal to create an admin user:

python manage.py createsuperuser

 You will need to provide a username, email address and password.

4.4 Start the development server and access the management background

Run the development server:

python manage.py runserver

 Visit http://localhost:8000/admin/ (or your development server address) to open the admin backend login page.  (or your development server address) to open the management backend login page. 

4.5 Use the created administrator account to log in to the management backend

        Once logged in, you will see the admin control panel where you can manage your registered models. You can add, edit, and delete model objects, view details, and perform other administrative operations.

 You are seeing this error because of settings in your Django configuration file  DEBUG = True. Change it to this Falseand Django will display a standard 404 page.

Refresh the page as follows:

        With the admin backend, you can easily manage your application's data without writing additional code. It provides a convenient interface for managing your application's backend data. Please note that some features are provided by default in the admin, but you can also customize the admin interface to meet your specific needs.

        These are the basic steps for using Django to manage the background. You can register multiple models in your application and manage them in the admin.

5 Routing and Views

        In Django, routing (also known as URL mapping) is used to define the relationship between URLs and views, determining which view function will handle a particular URL request. Here are the basic steps for configuring routing in Django:

5.1 Create application urls.pyfiles:

        In your Django application directory, create a urls.pyPython file named . This file will contain the application's URL mapping.

urls.py5.2 Define the URL mapping in the application's file:

        Use Django's path()function or re_path()function (for regular expression matching) to define URL mappings. Each URL mapping associates a URL pattern with a view function. Here is urls.pythe basic structure of an example file:

from django.urls import path
from . import views  # 导入应用程序的视图

urlpatterns = [
    path('url-pattern/', views.my_view, name='my-view-name'),
    # 更多 URL 映射...
]

         In this example, we import the application's view function, then use path()the function to map a URL pattern /url-pattern/to my_viewthe view function, and give the URL mapping a name my-view-name.

5.3 Configure project-level URL mapping:

        In addition to application-level URL mappings, project-level URL mappings need to be defined in the project's main URL configuration file . Typically, this is urls.pydone in the project's files, which include the application's URL mapping. For example:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),  # 包括 Django 管理后台的 URL 映射
    path('myapp/', include('myapp.urls')),  # 包括应用程序的 URL 映射
    # 更多项目级别的 URL 映射...
]

 In this example, we use include()the function to include the application's URL map into the project's main URL map and use /myapp/as the application's namespace.

5.4 Create view function:

        In Django, views are Python functions or classes that handle web requests and generate web responses. View functions receive HTTP requests, perform corresponding logic based on the request, and then return an HTTP response, usually an HTML page.

        In your application's view file (usually views.pya file), write the view function to handle the request pointed to by the URL map. View functions receive requests and return responses.

from django.http import HttpResponse

def my_view(request):
    return HttpResponse("Hello, World!")

 Here is a simple example where the view function returns an HTTP response containing the text "Hello, World!"

5.5 Test routing:

        After starting the Django development server, you can access the configured URL mapping in a browser and view the response of the view function.

        These are the basic steps for configuring routing in Django. You can add more URL mappings and view functions to build your web application based on your application needs. Routing is an important tool for associating URLs with views and functionality.

6 Django templates

          Django templates are a powerful tool for generating dynamic HTML content. It allows you to pass data from views to templates, and then use template tags and template syntax to render the data in the templates. The following are the basic concepts and usage of Django templates:

6.1 Create template file

        In the application directory of a Django project, there is usually a templatesfolder named where template files are stored. In this folder, you can create HTML files that will be used to render your pages. For example, you can create a my_template.htmlfile.

6.2 Passing data to templates

        In the view function, you can use the context to pass data to the template. Typically, you would wrap the data in a dictionary and then pass the dictionary to the template. Example:

from django.shortcuts import render

def my_view(request):
    my_data = {'name': 'John', 'age': 30}
    return render(request, 'my_template.html', {'data': my_data})

         In this example, my_datathe data from the dictionary is passed to 'my_template.html'a template named and stored in datathe variable.

6.3   Using Template Tags

         The Django template engine provides some built-in template tags for inserting dynamic content, loops, and conditional statements into templates. Here are some examples: For example, in a template the following code can be used to display the passed data

  • Use to { { variable }}insert the value of a variable.
  • Use {% for item in list %}...{% endfor %}to loop.
  • Use {% if condition %}...{% endif %}to make conditional judgments.
<p>Name: {
   
   { data.name }}</p>
<p>Age: {
   
   { data.age }}</p>

 6.4  Template inheritance

        Django templates support template inheritance, which allows you to create a base template (for example, the structure and layout of a page) and then extend it in other templates. This way, you can reuse the same structure in every page. {% extends "base_template.html" %}To use template inheritance, you can use the and tags in your template {% block content %}...{% endblock %}.

For example, you can create a base template base_template.htmland then extend it in other templates:

<!-- base_template.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>
<!-- other_template.html -->
{% extends "base_template.html" %}

{% block title %}Page Title{% endblock %}

{% block content %}
<p>This is the content of the page.</p>
{% endblock %}

 6.5  Template filters

         Django templates also support filters, which are used to process variables in the template. Filters are commonly used to format dates, strings, numbers, etc. For example, { { my_date|date:"Y-m-d" }}a date will be formatted. This is just a basic concept about Django templates. Django provides rich template syntax and functions for building complex dynamic pages.

        In summary, Django is a complete web framework suitable for web development projects of all sizes, from small websites to large enterprise applications. It provides a rich set of features and tools that enable developers to quickly build high-quality web applications. If you're a Python developer and want to build powerful web applications, Django is definitely worth considering.

Guess you like

Origin blog.csdn.net/qq_35831906/article/details/132581491
Recommended