Lesson 3 Python Web Enterprise Portal - templates and databases

catalogue

3.1 concept of formwork

3.1.1 overview of Django template

3.1.2 static resource configuration based on Django template

3.2 develop "scientific research base" module

3.2.1 making basic pages of portal website

3.2.2 page reuse based on Django template

3.2.3 transfer dynamic parameters to the template

three point three   Develop "company profile" module

  3.3.1 making side navigation bar

3.3.2 Django database model

3.4.3 optimize the background management system

3.1 concept of formwork

3.1.1 overview of Django template

In the last lesson, in order to quickly generate HTML, we directly hard coded the content corresponding to HTML into Python code and returned it. This method is intuitive and can quickly design the project structure, but directly coding the HTML content into Python code itself is not a good implementation method. Because the background Python code writing and the front-end HTML code design are two different tasks, they are generally completed by two teams respectively, and interact through the designed interface protocol. In order to effectively solve this problem, Django provides a template mechanism, which allows the back-end server to call and render the front-end HTML page with only a few changes.

The templates provided by Django are usually used to process HTML, which is essentially a kind of text. In short, Django embeds some special characters in ordinary HTML files. At this time, the HTML file is called a template, and these special characters can be summarized into two types: variables and template tags.

Variables are enclosed by two braces. The general form is:

{{ name }}

Variable provides a method to dynamically generate page content, so that the back-end server can dynamically insert variable values into HTML when rendering HTML pages.

The template label is surrounded by braces and a percent sign. The general form is:

{% if today_is_weekend %}
    <p>Welcome to the weekend!</p>
{% else %}
    <p>Get back to work.</p>
{% endif %}

The above template statements are similar to Python's if conditional judgment, and can perform logical flow control in HTML.

3.1.2 static resource configuration based on Django template

Based on Django's template mechanism, this section will further configure the static resources of each application module, and finally jump to each sub page through the Bootstrap navigation bar on the home page.

First, edit the home page module homeApp, and add links to each sub page in the home page by using the Bootstrap navigation bar component (the concept and basic usage of the Bootstrap navigation bar component can refer to the Bootstrap official website). Since the Bootstrap framework needs to be used for page design, first ensure that the js, css, fonts and other configuration files required by Bootstrap have been correctly imported in the static folder under the project root directory. For specific import methods, please refer to the previous lesson.

This section no longer uses Python hard coding to generate HTML, but directly uses the render function provided by Django to render the HTML template. First, create a new Templates folder under the homeApp folder (note that the folder name must be templates) to store HTML template files. Then create a new home.html file in the Templates folder, which is the home page file. Edit home.html and reference the configuration file corresponding to Bootstrap in the header. The code is as follows:

{% load static %}
<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hengda Technology(Teaching example website)</title>
    <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 'css/style.css' %}" rel="stylesheet">
    <script src="{% static 'js/jquery.min.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
</head>

<body>
</body>

</html>

The above code first introduces the {% load static%} statement. Here, the static tag provided by Django template is used. By importing this tag, you can locate the static resources of the project through the keyword static in the page. Finally, all static file resources can be referenced in the form of "{% static 'css/bootstrap.css'%}". The above reference method is the core part of Django template. This static resource reference method will be widely used later. Readers need to firmly grasp this method.

Next, in the < body > tab section, reference the ready-made navigation bar component nav provided by Bootstrap to include links to each sub page. The detailed code is as follows:

<body>
    <!-- Navigation bar -->
    <nav class="navbar navbar-default" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#bs-example" aria-expanded="false">
                    <span>navigation bar</span>
                </button>
            </div>
            <div class="collapse navbar-collapse" id="bs-example">
                <ul class="nav navbar-nav" style="width:100%;">
                    <li class="active nav-top">
                        <a href="{% url 'home' %}">home page</a>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            Company profile</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'aboutApp:survey' %}">Enterprise overview</a></li>
                            <li><a href="{% url 'aboutApp:honor' %}">Honorary qualification</a></li>
                        </ul>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            news information</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'newsApp:company' %}">important news </a></li>
                            <li><a href="{% url 'newsApp:industry' %}">Industry news</a></li>
                            <li><a href="{% url 'newsApp:notice' %}">Notice announcement</a></li>
                        </ul>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            Product Center</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'productsApp:robot' %}">
                                    Household robot</a></li>
                            <li><a href="{% url 'productsApp:monitoring' %}">
                                    Intelligent monitoring</a></li>
                            <li><a href="{% url 'productsApp:face' %}">
                                    Face recognition solution</a></li>
                        </ul>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            Service support</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'serviceApp:download' %}">
                                    Data download</a></li>
                            <li><a href="{% url 'serviceApp:platform' %}">
                                    Face recognition open platform</a></li>
                        </ul>
                    </li>
                    <li class="nav-top">
                        <a href="{% url 'scienceApp:science' %}">Scientific research base</a>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#"Class =" dropdown toggle on "data toggle =" dropdown "> talent recruitment</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'contactApp:contact' %}">Welcome to consult</a></li>
                            <li><a href="{% url 'contactApp:recruit' %}">Join Hengda</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>
</body>

In the above code, the class = "dropdown NAV top" is used to call the drop-down menu of the navigation bar. Note that in the < a > label part of each link, the href attribute uses the template label {% url 'reverse path'%} provided by Django to reverse find the access path. The search method is "Application Name: function name" If there is no application name, it can not be used. For example, the home page only adopts the following form without application name:

<a href="{% url 'home' %}">home page</a>

The specific reverse parsing form corresponds to the previously configured url route. For example, when configuring the "enterprise profile" page, the application name app_name = 'aboutApp' is defined in the urls.py file of the application, and the secondary route is bound:

path('survey/', views.survey, name='survey'),  # Enterprise overview

The above route defines the function name as survey, so the final reverse parsing form in the template is:

"{% url 'aboutApp:survey' %}"

This reverse URL parsing method is mainly used in HTML to facilitate the transformation of the root access path. For example, it can be accessed on the development server http://127.0.0.1:8000/aboutApp/survey/   To browse the enterprise profile page, but when the whole project is deployed to the production server, it is obviously inconvenient to modify all access paths globally. Therefore, a better way is to set the name for each route, and then use the reverse parsing method to dynamically find the current corresponding access website according to the name.

Finally, in order to access the home page normally, you need to modify the home processing function in the views.py file under the homeApp application. The modification code is as follows:

from django.shortcuts import render

# Create your views here.
def home(request):
    return render(request, 'home.html')

In addition, since the newly created shared static resource folder is under the project root path, you need to tell Django template the location of the currently shared static resource path. Open the settings.py file under the project configuration folder hengDaProject and add the static resource path setting at the end of the file:

import os
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

Run the project, and the effect picture is as follows. Click each link on the home page to jump to the specified sub page normally, and click the browser return button to return to the home page.

3.2 develop "scientific research base" module

3.2.1 making basic pages of portal website

The previous courses have completed the basic framework setting of each application. This section starts to develop the "scientific research base" module, and only needs to write the corresponding access page. This section focuses on the skills of Bootstrap design page and the basic django back-end template reuse method.

First, complete the basic configuration of the backend. The "scientific research base" module corresponds to the scienceApp application, and the view access function is the science function in the views.py file under the application. Create a new templates folder under the scienceApp folder, and then create a new science.html file under the templates folder for page access. Referring to the development process in the previous section, modify the science function as follows:

from django.shortcuts import render

# Create your views here.
def science(request):
    return render(request, 'science.html')

Directly return the science.html file under the scienceApp application to the front-end browser for display through the render function. Note here that Django will automatically find the template file in the folder named templates under each application, so there is no need to provide the templates path when using the render function for page rendering. Next, focus on the page design of science.html, and mainly introduce the page layout of portal website based on Bootstrap and CSS style setting method.

(1) Make page header

Refer to the home.html file structure under the homeApp application to import the basic Bootstrap configuration file. Edit the code of science.html as follows:

{% load static %}
<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hengda Technology|Scientific research base</title>
    <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 'css/style.css' %}" rel="stylesheet">
    <script src="{% static 'js/jquery.min.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
</head>

<body>
</body>

</html>

The first line is the static resource tag used to import the Django template. In the < head > tag part, first declare the metadata information, use utf-8 Chinese coding, and the initial adaptation width of the web page is the device width, which is used to support responsive design< The title > tab section displays the page title. Next, import the necessary CSS and js files of Bootstrap through the < link > and < script > tags respectively. In addition, the custom style.css file can be imported to facilitate personalized style setting.

Since all pages adopt the Bootstrap framework, the static configuration file corresponding to Bootstrap is placed in the static folder of the project root directory to facilitate other applications to share the resource. After configuring the < head > section, you need to start the page body design in the < body > section.

The header of the page can be divided into upper and lower parts. The first part includes the enterprise logo picture (on the left) and the explanatory text with small icons such as telephone and mailbox (on the right). The second part is the navigation bar. When using Bootstrap for page layout, 12 grids are allocated to each row. For the first line of the head, a 6-3-3 grid structure can be adopted, that is, in the case of large screen, the enterprise Logo Icon occupies 6 grids, while the telephone and mailbox occupy 3 grids respectively, accounting for a full line. On a small screen, such as a mobile phone, it is impossible to place logo pictures and explanatory text in one line at the same time. Considering the beauty of the page layout, the explanatory text will be hidden at this time. According to the above analysis, add the following code in the < body > section:

<body>
    <div class="container top">
        <div class="row">
            <div class="col-md-6">
                <a>
                    <img class="img-responsive" src="{% static 'img/logo.jpg' %}">
                </a>
            </div>
            <div class="col-md-3 hidden-xs">
                <a class="phone ant">
                    <span class="glyphicon glyphicon-phone"></span>Tel: 400 1111 0000 &nbsp; &nbsp;
                </a>
            </div>
            <div class="col-md-3 hidden-xs">
                <a class="mail ant">
                    <span class="glyphicon glyphicon-envelope"></span>Email: hengda@126.com
                </a>
            </div>
        </div>
    </div>
</body>
  • Outer div style: the above code first encapsulates the content in the container, so that the page content is limited to the specified width, which is suitable for responsive layout. A new top style class is created behind the container style class. This class is not the default style class provided by Bootstrap, but needs to be created manually. It needs to be edited in style.css later to set the margin, content color and other styles of the whole Div;
  • Internal div style: divide the content into three parts in < div class = "row" > and use the styles col-md-6, col-md-3 and col-md-3 to set the grid occupied by each part of the content. The hidden XS style means that this part of the content is not displayed on the small screen. All specific contents are implemented with < a > tags. The website logo image adopts the responsive img responsive image provided by Bootstrap to control the style, that is, the image will adaptively adjust the image size according to different browser resolutions. Note here that the image reference method src="{% static 'img/logo.jpg'%}". Like static css and js files, the static template tag system can accurately find the logo.jpg file and embed it into the page (all static images are placed in the "root directory / static/img" directory);
  • Icon style: phone, email and other descriptive text are displayed using the small icon classes phone and mail provided by Bootstrap (for the use of Bootstrap icons, please refer to the Bootstrap official website). In addition, in order to set the style of small icons, a custom ant class style is added after the style, which will be added later in the style.css file.

  Next, find the style.css file in the static/css folder (if not, add it manually), edit the style.css file and add the corresponding style settings:

.top{
    margin-top: 10px;
}

The above modification makes the entire div 10 pixels away from the upper boundary. Because the small icon is carried in the < a > tag, the default color is dark blue, and the website text designed in this book adopts dark gray style, so it is necessary to overwrite and rewrite the phone and mail icon styles provided by Bootstrap. Continue adding code in the style.css file:

.phone{
    color:#666;
    float: right;
}
.mail{
    color:#666;
    float:right;
}

The attribute float:right in the above code can make the icons arranged to the right. In addition, because the icon is embedded in the < a > label, there will be a default underline when the mouse moves over or clicks the icon. Here, add ant style to cancel the underline:

Run the project and access it through the browser http://127.0.0.1:8000/scienceApp/science/ View page effects. It should be noted here that many browsers (such as 360 browser and Firefox browser) have caching function. Therefore, when css files are modified, sometimes the modified effect cannot be displayed immediately. The solution is to set the cache function of the browser, which can be set to automatically clean the cache when the browser is closed.

The renderings are as follows:

Next, we make a page navigation bar. Previously, we have used the navigation bar of Bootstrap as a tool to jump to the home page. This section will continue to use this component and make some style adjustments on the original basis. Find the home.html file in the homeApp application templates folder, copy the < NAV > part of the navigation bar into the < body > tab of science.html, save and start the project to check whether the effect is normal. The effects are as follows:

  Next, you need to adjust the navigation bar style, including the top and bottom margins and the spacing of navigation bar entries. In addition, the response action attributes on the navigation bar, such as moving the mouse in and out, clicking, etc., also need to be adjusted to make their interaction more beautiful and reasonable. Edit the style.css file and add the following code:

/* Navigation bar default attribute settings */
.navbar-default{
	margin-bottom:0px;            /* Adjust bottom margin to 0 */
	border:0px;                    /* Remove border */
    background-color:#e7e7e7;    /*  Set navigation bar background color*/
    margin-top: 30px;              /* Sets the top margin of the navigation bar */
}
/* Properties when the navigation bar column is activated */
.navbar-default .navbar-nav .active a, 
.navbar-default .navbar-nav .active a:hover, 
.navbar-default .navbar-nav .active a:focus{
	background-color:#005197;   /*  Set the background color to dark blue*/
	color:#fff;                 /*  Set the foreground text color to white*/
}
/* First level menu mouse over properties */
.navbar-default .navbar-nav li a:hover{
	color:#fff;
	background-color:#005197;
}
/* Properties when the first level menu is clicked to expand */
.navbar-default .navbar-nav li.open a.on{
	color:#fff;
	background-color:#005197;
}
/* Drop down menu inner margin */
.dropdown-menu{
	padding:0px;
}
/* Secondary menu label properties */
.dropdown-menu li a{
	padding-top:10px;
	padding-bottom:10px;
    color:#777;
    text-align:center;
}
/* First level menu width and text alignment */
.nav-top{
	width:14%;
	text-align:center;
}

  Save the file and run the project to see the effect. Note that the secondary drop-down menu will not be displayed until you click the primary menu when using the navigation bar. In fact, you often want to automatically expand the secondary drop-down menu when you move the mouse to the primary menu (mouseover feature), and the secondary menu will automatically collapse when you move the mouse away. At this time, you need to use JavaScript to dynamically adjust the mouseover attribute of the drop-down menu. The expansion of the drop-down menu can be realized by adding an open class to the mouseover attribute of the drop-down menu, and the folding of the drop-down menu can be realized by removing the attribute. Specifically, add JavaScript code at the end of < body >, as follows:

<script>
    $(function () {
       $(".dropdown").mouseover(function () {
            $(this).addClass("open");
        });
        $(".dropdown").mouseleave(function () {
            $(this).removeClass("open");
        });
    });
</script>

So far, the production of the whole page header has been completed. The renderings are as follows:

  (2) Make advertising banners

This section mainly uses the responsive picture component provided by Bootstrap to display the large-size horizontal chart below the navigation bar.

To make it easier to distinguish, first insert a split line between the navigation bar and the banner. Next to the < NAV > label added in the previous section, add a < div > below to display the split line:

<div class="line"></div>

Add the style settings of the split line in style.css:

.line{
    height:3px;
    width:100%;   /* Make the width occupy the whole screen width */
    background:#005197;
}

The effects are as follows:

  Next, add the html code corresponding to the advertising banner:

<div class="container-fluid">
    <div class="row">
        <img class="img-responsive model-img" src="{% static 'img/science.jpg' %}">
    </div>
</div>

  For aesthetic consideration, the width of the advertising banner is set to be the same as that of the navigation bar, that is, it occupies the whole screen width. Therefore, the container fluid style provided by Bootstrap can achieve this effect. The image adopts img responsive responsive style, which can adaptively adjust the image size according to the browser window width. Its src attribute points to the science.jpg image in the static/img folder, and uses the template label {% static%} provided by Django to find resources.

The renderings are as follows:

  (3) Make page body

The main part of the "scientific research base" page includes the title with a pull line, some introductory words and pictures. The basic structure is as follows:

    <div class="container">
        <div class="model-details-title">
            Introduction to scientific research base
        </div>
        <div class="model-details">
        </div>
    </div>

The outer layer defines a container to limit the main body display area, and two div are defined in the container to display the main body title and main body details.

Add the style class model details title of the body title in the style.css file:

.model-details-title{
	padding:15px 0px;
	font-size:18px;
	border-bottom:1px #005197 solid; /*  Add a blue border at the bottom*/
	color:#005197;
	margin-bottom:10px;
	margin-top:10px;
}

The above style makes some adjustments to the font and margins. In addition, a blue lower border line can be constructed as a dividing line by setting the lower border bottom.

The main body details are some explanatory words and pictures about the "scientific research base". Common HTML tag elements such as < p >, < H3 >, < H5 > are used for page design. The detailed code is as follows:

<div class="model-details">
    <p>
        Over the past two decades, Hengda has been committed to building a corporate culture of "high ambition, a promise of a thousand junks"...
    </p>
    <img class="img-responsive" src="{% static 'img/kyjd.jpg' %}">
    <h3>Research direction</h3>
    <h5>Robot navigation:</h5>
    <p>
        Multi sensor path planning, integrated platform of Internet of things, remote human-computer interaction and enhanced learning control.
    </p>
    <h5>Human behavior recognition:</h5>
    <p>
        Single user behavior recognition, human bone big data analysis, robust feature extraction, multi-user behavior recognition.
    </p>
    <h5>Face attribute recognition:</h5>
    <p>
        Face detection, attribute analysis, pedestrian recognition.
    </p>
</div>

In order to further beautify the page, set the style of the main content, including the line height of text, alignment, picture position, etc. by adding the following code to the style.css file:

/* Text paragraph */
.model-details p{
	line-height:30px;
	text-indent:2em;
	text-align:justify;
	text-justify:inter-ideograph;
}
/* Subject image */
.model-details img{
	margin:0px auto;
}

The effect is shown in the following figure:

  (4) Make footer

The footer mainly includes site map and copyright. The site map can be used to inform the search engine of the website and the importance of the page, so as to help the site get better collection. The copyright part is mainly used to indicate the filing information of the production site. Website filing is to report the reasons to the competent authority for filing for future reference. Its purpose is to prevent illegal website business activities on the Internet and combat the dissemination of bad Internet information. If the website is not filed, it is likely to be shut down after investigation. Because filing takes a long time, if the website project is determined to be approved, it is recommended to enter the filing process immediately at the beginning of development. The detailed filing method of the website will be explained in later courses. This course only completes the basic page design.

The footer is designed as follows:

    <div class="container web-footer">
        <!-- Site map -->
        <div class="row" id="map-footer">
        </div>
        <!-- copyright -->
        <div class="row" id="patent-footer">
            <p> © 2021 Python Web Copyright enterprise portal | Soviet ICP Bei 19006378 </p>
        </div>
    </div>

The site map and copyright of the above code are embedded in two div's of class="row" respectively. The content of the outer layer is limited by the style class = "container web footer", where container is the container style class provided by Bootstrap and web footer is an additional custom style class. Edit the style.css file and add the web footer style as follows:

Next, the site map is made. The overall Bootstrap grid layout is 2-2-2-2-4, which is divided into 5 columns. The first 4 columns are used to place website Web links, and the last column is used to place QR code pictures. The specific HTML codes are as follows:

<div class="row" id="map-footer">
    <div class="col-md-2">
        <dl>
            <dt>Company profile</dt>
            <dd><a href="{% url 'aboutApp:survey' %}">Enterprise overview</a></dd>
            <dd><a href="{% url 'aboutApp:honor' %}">Honorary qualification</a></dd>
        </dl>
    </div>
    <div class="col-md-2">
        <dl>
            <dt>Product Center</dt>
            <dd><a href="{% url 'productsApp:robot' %}">Household robot</a></dd>
            <dd><a href="{% url 'productsApp:monitoring' %}">Intelligent monitoring</a></dd>
            <dd><a href="{% url 'productsApp:face' %}">Face recognition solution</a></dd>
        </dl>
    </div>
    <div class="col-md-2">
        <dl>
            <dt>Service support</dt>
            <dd><a href="{% url 'serviceApp:download' %}">Data download</a></dd>
            <dd><a href="{% url 'serviceApp:platform' %}">Face recognition open platform</a></dd>
        </dl>
    </div>
    <div class="col-md-2">
        <dl>
            <dt>Talent recruitment</dt>
            <dd><a href="{% url 'contactApp:contact' %}">Welcome to consult</a></dd>
            <dd><a href="{% url 'contactApp:recruit' %}">Join Hengda</a></dd>
        </dl>
    </div>
    <div class="col-md-4" id="wx">
        <p>Scan QR code and follow us</p>
        <img class="qrimg" src="{% static 'img/qr.png' %}" alt="wx">
        <p>Customer service hotline:<b style="font-size:20px">400 111 2222</b></p>
    </div>
</div>

Each column of the above code adopts the < DL >, < DT >, < DD > Table labels provided by HTML5. The outermost layer uses < DL > to indicate that this is a table, < DT > label is used to indicate the table title, and < DD > is used to indicate the specific content. Each item in the table includes other page links through the embedded link < a > tag. Each link uses the reverse routing method provided by the Django template to get the access website.

Next, you need to make some style adjustments to the above HTML, edit the style.css file, and add the following contents:

#map-footer{
	background-color:#3A3A3A;        /*  Set the background color gray for the entire site map*/
}
#map-footer dl{
	text-align:center;               /* Site link text alignment */
	margin-top:40px;                 /* Sets the margin between the table and the top edge */
}
#map-footer dt{
	padding:3px;                     /* The inner margin of the table title is 3 pixels */
	color:#fff;                      /*  The table title color is white*/
}
#map-footer dd{
	padding:3px;                     /* The inner margin of the table content is 3 pixels */	
}

/* QR code advertisement text style setting */
#map-footer p{
	margin-top:20px;
	margin-bottom:10px;
	color:#fff;
	font-size:16px;
}
#map-footer a{
	color:#A6A6A6;                   /*  Site link text color settings*/
	font-size:13px;                  /* Site link text size settings */
}
#map-footer a:hover{
	color:#fff;
	text-decoration:none;             /* Remove the underline that appears when the site link mouse moves */
}
#wx{
	text-align:center;                /* Align QR code Center */
}
.qrimg{
	max-width: 170px;                 /* The maximum width of QR code is 170 pixels */
}

Finally, add the corresponding css style to the copyright part:

#patent-footer{
	text-align:center;
	background-color:#3A3A3A;
}
#patent-footer p{
	margin-top:10px;
	padding-right:80px;
	color:#8d8d8d;
	font-size:11px;
}

So far, the design of the front-end web page of the "scientific research base" module has been completed. Based on this, the subsequent content will generate a website template in the form of component reuse for use by other modules. At present, the complete renderings are as follows:

 

3.2.2 page reuse based on Django template

  The so-called page reuse is to extract the same part of each page of the website as a shared page. Other pages only need to include the shared page when making. This method has two obvious advantages:  

  • It can significantly reduce the amount of front-end code;
  • When the shared part of each page needs to be modified, for example, the enterprise logo Icon needs to be replaced. At this time, only the shared page needs to be modified, and there is no need to change each page separately;

In this project, each shared page is placed in the templates folder under the root directory of the project. When other applications create pages, they only need to include the shared pages under this folder.

The template tags provided by Django for page reuse mainly include the following two:

(1) Inherit the tag, and the call form is as follows:

{% extends "base.html" %}

Through the use of this tag, you can directly inherit the page content of base.html.

(2) The dynamic content declaration label is called in the following form:

{% block content %}
{% endblock %}

Where block and endblock are fixed label statements, followed by content that can be named by users. When using, the non shared part is declared with the tag, and the dynamic content is filled into the tag in this way when inheriting.

Next, we split the previously made pages according to dynamic and non dynamic content. The so-called non dynamic content refers to the content shared by each page, such as the page header, navigation bar, footer, etc. in the case. These contents are fixed in the portal. In contrast, the dynamic content is the unique part of each page that is different from other pages, such as the main part of the page in the case. This section will complete the creation of the sharing template. You need to extract the header, navigation bar and footer of the previously created page to make a separate sharing page, and then embed the {% block content%} {% endblock%} tag in the main part. When calling, you only need to inherit the template page, and then write the dynamic content to the tag.

First, create a file named base.html in the templates folder of the project root directory, which will be used as a shared template file. Copy the contents of the previously written science.html file to base.html, and then edit the following two places:

(1) In the < head > tab:

<title>Hengda Technology|Scientific research base</title>

Replace with:

<title>Hengda Technology|{% block title %}{% endblock %} </title>

Part of the title of the page in the above code is dynamic content, so a dynamic content declaration tag {% block%} needs to be embedded here, and the dynamic tag should be named title.

(2) Modify the advertising banner and main content of the page, which are generally different from each page, so delete the whole banner and main content, and then embed a dynamic content declaration label as follows:

{% block content %}
{% endblock %} 

  Since then, the template has been made. The complete base.html code is as follows:

{% load static %}
<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hengda Technology|{% block title %}{% endblock %} </title>
    <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 'css/style.css' %}" rel="stylesheet">
    <script src="{% static 'js/jquery.min.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
</head>

<body>
    <div class="container top">
        <div class="row">
            <div class="col-md-6">
                <a>
                    <img class="img-responsive" src="{% static 'img/logo.jpg' %}">
                </a>
            </div>
            <div class="col-md-3 hidden-xs">
                <a class="phone ant">
                    <span class="glyphicon glyphicon-phone"></span>Tel: 400 1111 0000 &nbsp; &nbsp;
                </a>
            </div>
            <div class="col-md-3 hidden-xs">
                <a class="mail ant">
                    <span class="glyphicon glyphicon-envelope"></span>Email: hengda@126.com
                </a>
            </div>
        </div>
    </div>

    <!-- Navigation bar -->
    <nav class="navbar navbar-default" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example"
                    aria-expanded="false">
                    <span>navigation bar</span>
                </button>
            </div>
            <div class="collapse navbar-collapse" id="bs-example">
                <ul class="nav navbar-nav" style="width:100%;">
                    <li class="active nav-top">
                        <a href="{% url 'home' %}">home page</a>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            Company profile</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'aboutApp:survey' %}">Enterprise overview</a></li>
                            <li><a href="{% url 'aboutApp:honor' %}">Honorary qualification</a></li>
                        </ul>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            news information</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'newsApp:company' %}">important news </a></li>
                            <li><a href="{% url 'newsApp:industry' %}">Industry news</a></li>
                            <li><a href="{% url 'newsApp:notice' %}">Notice announcement</a></li>
                        </ul>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            Product Center</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'productsApp:robot' %}">
                                    Household robot</a></li>
                            <li><a href="{% url 'productsApp:monitoring' %}">
                                    Intelligent monitoring</a></li>
                            <li><a href="{% url 'productsApp:face' %}">
                                    Face recognition solution</a></li>
                        </ul>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#" class="dropdown-toggle on" data-toggle="dropdown">
                            Service support</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'serviceApp:download' %}">
                                    Data download</a></li>
                            <li><a href="{% url 'serviceApp:platform' %}">
                                    Face recognition open platform</a></li>
                        </ul>
                    </li>
                    <li class="nav-top">
                        <a href="{% url 'scienceApp:science' %}">Scientific research base</a>
                    </li>
                    <li class="dropdown nav-top">
                        <a href="#"Class =" dropdown toggle on "data toggle =" dropdown "> talent recruitment</a>
                        <ul class="dropdown-menu">
                            <li><a href="{% url 'contactApp:contact' %}">Welcome to consult</a></li>
                            <li><a href="{% url 'contactApp:recruit' %}">Join Hengda</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="line"></div>

    {% block content %}
    {% endblock %} 

    <script>
        $(function () {
            $(".dropdown").mouseover(function () {
                $(this).addClass("open");
            });
            $(".dropdown").mouseleave(function () {
                $(this).removeClass("open");
            });
        });
    </script>
</body>

</html>

Next, we rewrite science.html to simplify the code by using the shared template base.html. First, inherit the base.html template file in science.html, and the code is as follows:

{% extends "base.html" %}
{% load static %}

According to the template made before, there are two dynamic tags that need to be filled with dynamic content. First, fill in the page title:

{% block title %}
Scientific research base
{% endblock %}

Then fill the advertising banner and main content into another dynamic label, as follows:

{% block content %}
<!-- Advertising banner -->
<div class="container-fluid">
    <div class="row">
        <img class="img-responsive model-img" src="{% static 'img/science.jpg' %}">
    </div>
</div>
<!-- Main content -->
<div class="container">
    <div class="model-details-title">
        Introduction to scientific research base
    </div>
    <div class="model-details">
        <p>
            Over the past two decades, Hengda has been committed to building a corporate culture of "high ambition and great promise", constantly absorbing and cultivating high-precision talents of artificial intelligence, and gradually formed...
        </p>
        <img class="img-responsive" src="{% static 'img/kyjd.jpg' %}">
        <h3>Research direction</h3>
        <h5>Robot navigation:</h5>
        <p>
            Multi sensor path planning, integrated platform of Internet of things, remote human-computer interaction and enhanced learning control.
        </p>
        <h5>Human behavior recognition:</h5>
        <p>
            Single user behavior recognition, human bone big data analysis, robust feature extraction, multi-user behavior recognition.
        </p>
        <h5>Face attribute recognition:</h5>
        <p>
            Face detection, attribute analysis, pedestrian recognition.
        </p>
    </div>
</div>
{% endblock %}

Since our shared template file is placed in the templates of the root directory, we need to configure it in the settings.py file so that each application can correctly reference the base.html file under this templates.

Edit the settings.py file in the hengDaProject folder and find the TEMPLATES field, which is where the project template needs to be configured. Modify DIRS as follows:

'DIRS': [os.path.join(BASE_DIR, 'templates')],

In the above configuration, add the templates folder under the project root directory BASE_DIR to the template search path, so that the shared template base.html can be found during page access. Note that the os library needs to be introduced into the header of the settings.py file:

import os

Here, the modification is completed. Let's run the system again, and then open the scientific research base page to see if it can render normally.

3.2.3 transfer dynamic parameters to the template

When visiting the "scientific research base" page, you can enter the website by http://127.0.0.1:8000/scienceApp/science/ To jump to the page, or you can log in to the home page first http://127.0.0.1:8000/ , and then click "research base" on the home page The link jumps to the page. A problem will be found here. After switching the page, the activation effect of the navigation bar does not switch synchronously, that is, after clicking the "scientific research base" page, the activation menu on the navigation bar is still "home page".

At this time, the navigation bar activation state conversion needs to be carried out according to the actual situation in the process of page rendering, that is, the background server will pass in different template parameters according to different rendering pages, and the page navigation bar will select different activation states according to the passed in parameters.

Specifically, first view the style code of the "home page" of the navigation bar (located in the base.html file). The style class used to control the activation status is the active style provided by Bootstrap:

<li class="nav-top active">
    <a href="{% url 'home' %}">home page</a>
</li>

In order to switch the active state, you need to dynamically add an active style to the < li > tag of the navigation link. When implementing, first indicate the id number of each < li > tag of the navigation bar to facilitate the discovery of page elements. For example, set the id for "scientific research base" as follows:

<li class="nav-top" id='science'>
    <a href="{% url 'scienceApp:science' %}">Scientific research base</a>
</li>

  Then find the id node through the embedded JavaScript code and add a style. The specific code is as follows:

<script type="text/JavaScript">
    $('#science').addClass("active");
</script>

At this time, you can activate the "scientific research base" link dynamically during the initial rendering of the page. The effect is shown in the following figure:

In this way, we can dynamically activate a navigation link through the code.

Here, notice how jQuery is used to find nodes in JavaScript code. Find the node $('#science') through the node id. Although the link activation setting of the "scientific research base" page can be realized, the search node is fixed and can only be science, while the base.html file is a shared template file. When other pages call, their navigation links also need to be activated. Therefore, the id number cannot be a fixed value, but a variable. Django provides the use of template variables, which are identified by double brackets: {variables}}. Continue to modify the above JavaScript code as follows:

<script type="text/JavaScript">
    $('#{{active_menu}}').addClass("active");
</script>

Here, the template variable {{active_menu}} is used to replace the fixed id value. In the process of page rendering, you only need to pass this variable in the background view function.

Open the views.py file in the scienceApp application and modify the science function as follows:

def science(request):
    return render(request, 'science.html',{'active_menu': 'science',})

The above code adds a third parameter when render returns. This parameter is composed of a Python dictionary, which is the variable to be passed to the template: the dictionary key is the variable name and the key value is the variable value. After modification, save all files and restart the project to check whether the navigation bar link switching effect is normal. The switching operations of navigation links in subsequent courses are all carried out according to the above steps, that is, first add an id number to the navigation link, and then pass active to the template in the corresponding render function during page rendering_ Menu variable.

  The renderings are as follows:

three point three   Develop "company profile" module

  3.3.1 making side navigation bar

This section starts with the basic page of the "company profile" module. according to Sample website The effect of the page shown is basically the same as that of the "scientific research base" page made in the previous lesson, and only one side navigation bar is added on the left side of the main part of the page. Next, enter the specific production steps.

According to the method of rendering the page in the previous lesson, first open the aboutApp application, create a templates folder under the application, and then create a web page file named survey.html under the folder. According to the page template created in the previous lesson, inherit the page content by inheritance, including page header, navigation bar and footer. The specific codes are as follows:

{% extends "base.html" %}
{% load static %}

{% block title %}
Enterprise overview
{% endblock %}

{% block content %}
<!-- Advertising banner -->
<div class="container-fluid">
    <div class="row">
        <img class="img-responsive model-img" src="{% static 'img/about.jpg' %}">
    </div>
</div>
<!-- Main content -->
{% endblock %}

The above code inherits the template base.html file through {% extensions "base. HTML"%}. For advertising banners, modify the corresponding static picture file path. The main part is not filled in temporarily, and the detailed main content design will be described in the next section.

In order to effectively render the survey.html file, open the views.py file under the aboutApp application and modify the view processing function survey as follows:

def survey(request):
    return render(request, 'survey.html',{'active_menu': 'about',})

Here, the first parameter of the render function directly returns the request, the second parameter passes in the name of the HTML file to be rendered, and the third parameter is to synchronously switch the active state of the navigation bar when the page is switched to "company profile", so you need to add active to the template_ Menu parameter (don't forget to add id to the "company profile" link in base.html). The renderings are shown below

  According to the above development method, develop the page honor.html corresponding to the honor and qualification module under the templates folder of the aboutApp application, and modify its view processing function Honor:

def honor(request):
    return render(request, 'honor.html',{'active_menu': 'about',})

So far, the two page frames under the "company profile" module have been made. It can be seen that through the reuse of templates, only a few lines of inheritance code can be used to completely import the previously made sub pages, which can greatly improve the project development efficiency.

Finally, there is a small problem left. If you are already in the "enterprise profile" page, you will find that the colors of the two links are the same when you move the mouse to the "honor and qualification" navigation link. In order to distinguish effectively, add the following code to the style.css file:

/* Secondary dish mouse move out attribute */
.navbar-default .navbar-nav li ul a:hover{
	color:#fff;
	background-color:#005197;
}
/* When the primary menu is activated, the secondary menu mouse moves out of date attribute */
.navbar-default .navbar-nav li.active ul a:hover{
	color:#fff;
	background-color:#022a4d;
}

Through the above settings, the links of the two sub modules will show different colors when the mouse is moved.

Next, we will make the side navigation bar in the main part to facilitate users to switch sub pages. according to Sample website The main body of the page can be divided into left and right parts. The left side is the side navigation bar, and the right side is the fixed position picture and introductory text. According to the page structure, the basic structure of HTML is designed as follows:

<div class="container">
	<div class="row row-3">
        <!-- Side navigation bar -->
		<div class="col-md-3">
        </div>
        <!-- Explanatory text and pictures -->
		<div class="col-md-9">	
        </div>
    </div>
</div>

The above code adopts a 3-9 grid layout for the page, with the side navigation bar accounting for 3 grids and the content on the right accounting for 9 grids. The container container is used to limit the main content of the whole page to the specified width and include it in the div of class=row, occupying a full line. Add an additional style ". row-3" for the row div, and edit the style.css file to add style settings:

.row-3{
	margin-top:30px; /* Set top margin */
}

The side navigation bar is implemented by the list component list group provided by Bootstrap, in which each link list item is represented by the style list group item. The specific code is as follows:

        <!-- Side navigation bar -->
        <div class="col-md-3">
            <div class="model-title">
                Company profile
            </div>
            <div class="model-list">
                <ul class="list-group">
                    <li class="list-group-item" id="survey">
                        <a href="{% url 'aboutApp:survey' %}">Enterprise overview</a>
                    </li>
                    <li class="list-group-item" id="honor">
                        <a href="{% url 'aboutApp:honor' %}">Honorary qualification</a>
                    </li>
                </ul>
            </div>
        </div>

In the above code, "{% url 'aboutApp:survey'%}" and "{% url 'aboutApp:honor'%}" are used to reverse find routes for later deployment. The model title and model list style classes are used to customize the navigation bar title and list style, edit the style.css file, and add the corresponding styles:

/*Side navigation bar Title Style*/
.model-title {
	text-align: center;
	color: #fff;
	font-size: 22px;
	padding: 15px 0px;
	background: #005197;
	margin-top: 25px;
}
/*Side navigation bar list item style*/
.model-list li{
	text-align:center;
	background-color:#f6f6f6;
	font-size:16px;
}
/*Side navigation bar list item link style*/
.model-list li a{
	color:#545353;
}
/*Side navigation bar list item link active style*/
.model-list li a:hover{
	text-decoration:none;
	color:#005197;
}

Through the above style settings, you can complete the basic design of the side navigation bar. Next, style the page switching link of the side navigation bar. The general idea is consistent with the design of the primary navigation bar link. When the side navigation bar link is switched, the link text in the active state is blue, and other link text is gray, so that the user can clearly see which sub page is currently in after switching the side navigation bar. The implementation method can refer to the design process of the primary navigation bar. It only needs to pass the secondary menu variables from the background to the template, and then the front end can dynamically add an active class to the < li > tag through the addClass function of the JavaScript script. First, edit the style.css file and add the following code:

/*Side navigation bar active style*/
.model-list li.active{
	text-align:center;
	background-color:#f6f6f6;
	font-size:16px;
	border-color: #ddd;
}
/*Mouse over style when side navigation bar is active*/
.model-list li.active:hover{
	text-align:center;
	background-color:#f6f6f6;
	font-size:16px;
	border-color: #ddd;
}
/*Link style when the side navigation bar is active*/
.model-list li.active a{
	color:#005197;
}

The above css code can make the link text display blue when a link in the side navigation bar is active, which is convenient for users to browse and identify. Next, add JavaScript code at the end of the < body > tag of the base.html file:

<script type="text/JavaScript">
    $('#{{sub_menu}}').addClass("active");
 </script>

Finally, modify the views.py file in the aboutApp application, re edit the survey and honor functions, and add additional submenu variables when the render function returns:

def survey(request):
    return render(request, 'survey.html', {
        'active_menu': 'about',
        'sub_menu': 'survey',
    })

def honor(request):
    return render(request, 'honor.html', {
        'active_menu': 'about',
        'sub_menu': 'honor',
    })

Through the above modification, the secondary menu switching of the side navigation bar can be realized. So far, the development task of the side navigation bar has been completed. Next, continue to improve the "enterprise profile" page. The right part of the main body is fixed introductory text and pictures, and its design is basically consistent with the page of "scientific research base", including title, underline, paragraph text and pictures, which will not be described here. The final effect of "enterprise profile" is shown in the figure below.

  From the final effect, the text and pictures of the main parts of the enterprise profile are static resource files, that is, they do not need to interact with the background, and are called directly in the HTML file. This kind of page is called static page, and its development is relatively simple. Next, we will learn how to build dynamic pages through the Django database model.

3.3.2 Django database model

In the process of computer information processing, it is often necessary to save or process a large amount of data. At this time, it is necessary to use the database to store and manage these data. In short, a database is a warehouse for storing data. This warehouse is organized and stored according to a certain data structure. The data in the database can be managed through a variety of methods provided by the database. The database we usually talk about is actually the database management software including the database management system, which is mainly used to add, find, update and delete data. For a simpler image understanding, databases are the same as warehousing and logistics, but the difference is that they store different things.

In order to make Python language have good compatibility and portability for all kinds of database access, python has formulated a general standard for database access interface. All Python database engines comply with the DB-API specification specified in this standard. The switching and configuration steps of database engines are basically the same, which greatly facilitates Python's database operation.

To operate the database through Python, the general steps are to create the database, design the table structure and fields, use sqlite(MySql, PostgreSQL and other common databases) engine to connect the database, write the data access layer code, and call the data access layer in the business logic layer to perform the database operation. It is noted that the above database operation process is cumbersome, requiring developers to add, delete, query and modify data directly to the database, resulting in low development efficiency. Can developers operate the database directly facing the objects in the code? The answer is yes. This object-oriented database programming method is object relational mapping (ORM). Specifically, in ORM, the class name corresponds to the table name in the database, the class attribute corresponds to the field in the database, and the class instance corresponds to a row of data in the database table. The ORM framework is embedded in Django, which does not need direct database oriented programming, but completes the addition, deletion, modification and query of data tables through model classes and objects.
Specifically, Django has automatically provided a sqlite database to provide database operations for the project when the project is created, and has configured parameters for the use of the database. Open the settings.py file in the configuration folder hengDaProject and find the DATABASES field. The default configuration is as follows:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

You can see that the default database ENGINE engine of the project is django.db.backend.sqlite3, and the database path is the db.sqlite3 database file under the root directory of the current project (SQLite database is essentially a file). If other databases need to be used, the database configuration is set in this field. In the actual Web site deployment, SQLite database is generally not used, because the concurrency and response speed of the database are greatly limited, but the database can be used for development and testing in the development stage. How to configure and use MySql database in Django will be described in detail in the deployment phase of the later course.

After understanding the basic concept and configuration of Django database, we will carry out specific development through Django database model.

reference Sample website It can be seen that each honor obtained by the enterprise is displayed in the form of "1 picture + 1 brief text description". In order to facilitate the managers to manage the honor information in the later stage, it is necessary to abstract the current honor data and generate the corresponding data model in the database.

Django data model is database related, and database related code is usually written in the models.py file. First, open the models.py file in aboutApp and add the "honor" Award model to the file:

from django.db import models

class Award(models.Model):  # Honor model
    description = models.TextField(max_length=500, blank=True,null=True)  # Text description
    photo = models.ImageField(upload_to='Award/', blank=True)             # picture

The above code first imports the models module in django.db to facilitate the creation of database fields. Next, define an Award class corresponding to the "honor" model, which inherits from models.Model. Two fields are defined in the Award class: description and photo, which correspond to the text description and picture of the "honor" model respectively. The text description uses models.TextField for field declaration, and uses max_length parameter to set the maximum length allowed for this field. In addition, by setting the parameter blank=True, null=True indicates that the field is allowed to be empty. The picture information is declared with models.ImageField by setting upload_to parameter to define the image upload directory. The uploaded image information will be stored under the Award folder of the server media resource path.

In this example, only the text and image fields in Django database model are used. In addition, Django also provides many other useful fields, including integer data, character data, floating-point data, etc. for details, please refer to django official website.

Note that when using the Django model field, there are two fields for file upload: ImageField and FileField. Both of them need additional path settings, that is, the media resource file storage directory needs to be specified in the project. Since the project adopts the image ImageField field, it needs to be configured. Specifically, open the settings.py file under the configuration folder hengDaProject, and add the code at the end of the file:

# Add media resources
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

The above configuration can tell the interpreter that the storage root path of the media resource file (here refers to the image) of the current project is / media /, that is, all uploaded images are stored in the media folder under the project root directory, combined with the parameter upload in the ImageField field field of the database_ To, and the storage path of the final uploaded image is / media/Award.

Because we use the picture field, we need to install an additional image processing library, pilot:

pip install Pillow

After the model is created, you need to synchronize the created model to the database system. First enter the command in the terminal:

python manage.py makemigrations

At this time, the following results will be output at the terminal:

Migrations for 'aboutApp':
  aboutApp\migrations\0001_initial.py
    - Create model Award

At this point, you are ready to store the model data into the database. Open the migrations folder in the aboutapplication to view that 0001 has been created under the current folder_ Initial.py file, which is the locally created data model file to be synchronized. Note, however, that there is no real database synchronization at this time, and only the preparations for synchronization are completed. Next, enter the command:

python manage.py migrate

The output results are as follows:

​
Operations to perform:
  Apply all migrations: aboutApp, admin, auth, contenttypes, sessions
Running migrations:
  Applying aboutApp.0001_initial... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

At this time, the synchronization of the database model is really completed, that is, the corresponding data table has been created for the Award model in the database. Next, you can add, delete, query and modify the data of the database model. You can edit the data in the database directly in the python shell through code, but this method of adding, deleting, querying and modifying the database through code is not convenient and intuitive.

An enterprise portal is divided into two parts: foreground and background. The front desk mainly provides regular page access for ordinary users, who can browse basic information. In the background, the website administrator is responsible for viewing, adding, modifying and deleting website data. Developing a complete background management system is an extremely cumbersome work. Therefore, Django provides a ready-made and efficient background management system, which has automatically generated such a convenient background for us in the process of creating the project.

Specifically, Django can automatically generate a management module according to the defined model. Using Django's management function requires only two steps:

  • Create super administrator;
  • Register model class;

  To use Django's background management system, you first need to create a super administrator account to log in to the background system. Specifically, enter the command in the terminal:

python manage.py createsuperuser

Then, according to the prompt, enter the user name, mailbox and password (enter twice) to complete the creation of super user. After successful creation, the output is as follows:

Superuser created successfully.

This indicates that the super administrator has been successfully created. Next, start the project and visit: http://127.0.0.1:8000/admin , the access effect is as follows:

  Enter the created super administrator user name and password to log in to the background management system. As shown in the figure below:

After entering the background management system, you can see the models currently registered in the system, including Group and Users. This is the account management model provided by default. Click Users to see the following page:

  All current user data are listed on this page. Since we have not created other user data here, we can only see the super administrator account.  

In the background management system, you can easily operate the database model through the visual button and the default form provided by the system.

Now continue to complete the development task of this lesson. As can be seen from the above figure, there is no operation setting of the Award model on the main page of the current management system. This is because we created the Award model in the database, but did not register the model in the background management system, so the background management system cannot operate the model. If you need to register the model to the background management system, you only need to add the registration information corresponding to the model in the admin.py file. Specifically, open the admin.py file in aboutApp, and the editing code is as follows:

from django.contrib import admin
from .models import Award

class AwardAdmin(admin.ModelAdmin):
    list_display = ['description','photo']

admin.site.register(Award, AwardAdmin)

First, introduce the administrator module admin provided in Django, and then import the previously created Award class from the models.py file. Next, an honor management class named AwardAdmin is defined, which inherits from the ModelAdmin class in the admin module. Display list is set in AwardAdmin_ Display parameter, which adds the model fields to be edited, including text description field description and image field photo. Finally, bind the awaradmin class and the Award class through the admin.site.register function and register. Save all modifications and refresh the browsing page. You can see that the aboutapp group (corresponding to aboutapp application) is newly added in the background management system. In this group, you can operate the Award class, as shown in the figure:

Next, add several pieces of data to the Awards model through the background management system for later use. Click the Add button corresponding to the row of the Award to enter the data addition interface, as shown in the following figure:

When defining the Award model, there are two fields: description and photo, which correspond to the two fields in the background data addition interface one by one. Because the description uses a long text field TextField to declare, the background management system automatically forms a multi line input box for this field to facilitate users to input data, while the photo declaration uses the ImageField field, so the background management system automatically forms a file upload button to perform data addition. According to the input format, add a text description in the description, then click the Browse button to select a picture (note that the uploaded photo name does not contain Chinese), and finally click the Save button on the right to save the data.

Continue to add several similar Award data in the above way, and the final Award list is shown in the figure below:

At this point, all data in the Award model has been stored in the database file. It should be noted that for the image photo field, the image data is not directly stored in the database, but the corresponding image path is stored. The real storage path of the image is based on the media of the settings file_ URL and MEDIA_ROOT. Specifically, for this example project, you can check whether there are corresponding pictures in the media folder under the root directory of the current project (under the media/Award path).

In addition to adding data to the model, the deletion, modification and query of model data can also be realized through the background management system. The specific demonstration will not be carried out one by one here. With the above Award model data in the database, you can dynamically embed data into the page in the process of user requesting the page to realize the access of dynamic page. Next, we will explain how to extract model data from the database through Django and insert it into the template for dynamic page rendering.

Django provides a convenient ORM operation to manage the database model. When the user accesses the honor and qualification page, the request is distributed to the honor function in the views.py file through the routing url for processing. After receiving the request, the function first takes out all the data of the Award model from the database, and then embeds the data into the honor.html template file.

Re edit the honor function in the views.py file as follows:

from .models import Award

def honor(request):
    awards = Award.objects.all()
    return render(request, 'honor.html', {
        'active_menu': 'about',
        'sub_menu': 'honor',
        'awards': awards,
    })

First, import the Award model from the model.py file under the current application, and then get a query set through the objects.all() function of the model in the honor function and store it in the variable awards. When the page is rendered, the awards variable is added to the page as a parameter through the render function. This example obtains the model data information through the objects.all() function of Django model manager. In addition, Django also provides many other query functions, which can be referred to for details Official website . Here, we do not need to master all query statements at once, but only need to gradually learn the common calling methods through project examples in subsequent chapters.

  Let's start editing the honor.html page. According to the effect shown in the example website, the overall design of the "honor and qualification" page is consistent with the "enterprise profile" page, except that the main part displays the honors obtained by the enterprise in the form of picture list. The existing thumbnail component of Bootstrap (style class thumbnail) can be used for layout, which can be realized with a little modification. The initial design scheme is as follows:

<div class="col-md-9">
    <div class="model-details-title">
        Honorary qualification
    </div>
    <div class="row">
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="{% static 'img/honor1.jpg' %}">
                <div class="caption">
                    <p>2011 Joined the Internet association in</p>
                </div>
            </div>
        </div>
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="{% static 'img/honor2.jpg' %}">
                <div class="caption">
                    <p>2012 Joined the Internet association in</p>
                </div>
            </div>
        </div>
    </div>
</div>

  The above code contains two thumbnails, each of which includes a < img > tag for displaying the image and a < div > tag of class="caption" for displaying the description information corresponding to the image. Each thumbnail occupies 4 grids under the large screen browser and 6 grids on the small screen browser. The above code adopts the static page mode to explicitly write the image path and text description information in HTML, and can not dynamically modify the image and text data according to the database information. Next, you need to dynamically write data into HTML according to the awards parameter passed in by the background honor function, mainly through the template tag {% for%} {% endfor%}. The template tag can dynamically traverse the incoming variables to realize circular writing of page data. The specific codes are as follows:

<div class="col-md-9">
    <div class="model-details-title">
        Honorary qualification
    </div>
    <div class="row">
        {% for award in awards %}
        <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="{{award.photo.url}}">
                <div class="caption">
                    <p>{{award.description}}</p>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

The above code takes out each piece of data in awards one by one through the {% for award in awards%} statement and assigns it to the new temporary variable award. Each award contains one item of photo and description data. In the thumbnail, use the template variables {{award.photo.url}} and {{award.description}} to give dynamic content to the src attribute of < img > and the paragraph < p > respectively. In this way, thumbnails can be generated according to the actual number of entries in awards. The addition, deletion, query and modification of the page data no longer need the developer to change the code, but only need to operate the data through the background management system to complete the data update. The browsing effect after refreshing the page is shown in the following figure:

  It can be seen that the text information of each thumbnail has been correctly displayed, but the picture information is not displayed. The main reason is that there is no dynamic resource path media in the current debug mode_ Add the URL to static routing. Edit the urls.py file under the configuration folder hengDaProject and add the following code:

from django.conf import settings
from django.conf.urls.static import static

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

After saving the changes, refresh the web page again to see the correct effect picture, as shown below.

  So far, this section has completed the export and rendering of the database model. Through the development of the "honor and qualification" sub module in this section, it is believed that readers have mastered the production process of dynamic pages and basic database operation methods. Other pages of subsequent courses are realized by this dynamic page making method. Therefore, it is hoped that readers can firmly grasp the knowledge points of this section and practice more. For unclear places, they can analyze them in combination with the code of supporting resources of this course.

3.4.3 optimize the background management system

In the previous section, the use method of Django background management system is introduced. It is necessary for developers to master the use of the background management system, but the system is not friendly to non developers, including language (the default language of Django background management system is English) and interface design. This section focuses on how to optimize the background management system to facilitate the delivery of the website to actual customers in the future.

(1) Login interface optimization

Django takes English as the main language of the project by default when creating the project. Therefore, most fields in the background management system are English. First, the login interface is processed in Chinese.

Open the project configuration file settings.py and find the language in it_ Code field, which is used to set the language of the whole project. It needs to be changed to Chinese support here. In addition, you need to modify the time zone field TIME_ZONE is the time zone of China. The specific modifications are as follows:

LANGUAGE_CODE = 'zh-Hans'   # Set language to Chinese

TIME_ZONE = 'Asia/Shanghai' # Set China time zone

Save and start the project after modification. When you visit the background management system, you can find that the key fields have been converted from English to Chinese, and the effect is as follows:

 

  The default system name of the background management system provided by Django is "Django management". When it is actually delivered to customers, the background system name needs to be defined according to the website theme. Therefore, the background management system name needs to be modified next.

Open the admin.py file under the aboutapplication and add the code at the end of the file:

admin.site.site_header = 'Enterprise portal background management system'
admin.site.site_title = 'Enterprise portal background management system'

The above code modifies the header and page title of the management system respectively. After saving the modification, refresh the page, as shown in the figure below. Note here that since the project hengDaProject we created is a multi application project, the above code modification only needs to be placed in the admin.py file under any application to take effect.

  (2) Main interface optimization

  The main interface part first modifies the display of the data model. Because the Award model is created, you can see the words "Awards" displayed in English under aboutapp (it will be expressed in the plural form of the model name by default). Although developers know the meaning of the model, the English words are abrupt for non developers. I hope it can be changed to "Award". An effective solution is to create a Chinese alias for the model in the process of model creation, so that the alias can be used to replace the real name of the model in the background management system. Django provides a simple implementation method for this idea, which only needs to modify the Meta meta information of the model. Specifically, open the models.py file under the aboutapplication to add Meta meta information description for the defined Award model. The code is as follows:

from django.db import models

class Award(models.Model):  # Honor model
    description = models.TextField(max_length=500, blank=True,null=True)  # Text description
    photo = models.ImageField(upload_to='Award/', blank=True)             # picture

    class Meta:
        verbose_name = 'Awards and honors'
        verbose_name_plural = 'Awards and honors' 

Where verbose_ The name field is the alias defined by the model, verbose_name_plural is the plural form corresponding to the alias. After saving, refresh the page to see the effect shown in the following figure:

  Next, you need to modify the display of the application name aboutapp. For the tasks in this chapter, aboutapp needs to be modified to "company profile". The application name displayed by Django in the background by default is the name when the app is created. You need to modify the name of the app to meet the customization requirements. From Django   App will not be used after version 1.7_ Label, you need to use AppConfig to modify the app. Here we only need to apply__ init__.py, open the__ init__.py file, add the following code:

from os import path
from django.apps import AppConfig

VERBOSE_APP_NAME = 'Company profile'

def get_current_app_name(file):
    return path.dirname(file).replace('\\', '/').split('/')[-1]

class AppVerboseNameConfig(AppConfig):
    name = get_current_app_name(__file__)
    verbose_name = VERBOSE_APP_NAME

default_app_config = get_current_app_name(
    __file__) + '.__init__.AppVerboseNameConfig'

  This is mainly implemented by referring to the official Django reference document. The app alias is set by inheriting the AppConfig class. If this part of the code is difficult to understand, it can not be studied in depth for the time being. Mainly pay attention to VERBOSE_APP_NAME field, which can be modified to add an alias. Refresh the page after saving the changes. The effect diagram is shown in the following figure:

(3) List interface optimization  

  Click the model to enter the model list page, which displays all the data of the model. Note that each field of the model is still in English. Next, modify the model fields so that description and photo are displayed as "honor description" and "honor photo" respectively. The solution is basically the same as the modification of the model name, which is displayed by aliasing each field of the model. Re edit the description and photo fields in the Award model and add verbose for each field_ The name attribute is modified as follows:

from django.db import models

class Award(models.Model):  # Honor model
    description = models.TextField(max_length=500,
                               blank=True,
                               null=True,
                               verbose_name='Honor description')
    photo = models.ImageField(upload_to='Award/',
                            blank=True,
                            verbose_name='Honor photos')

    class Meta:
        verbose_name = 'Awards and honors'
        verbose_name_plural = 'Awards and honors' 

Refresh the page after saving the changes. The effect diagram is shown in the following figure:

Well, that's it. This class is over.  

Tags: Python Database

Posted on Wed, 15 Sep 2021 20:26:51 -0400 by n000bie