Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the detailed architecture process of web framework based on Django3.0?

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces how the detailed architecture process of the web framework based on Django3.0 is, and the content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

The following will compare the two versions and match the code error problems caused by the version change.

Getting started with Django

Today's websites are actually rich applications (rich application), just like mature desktop applications. Python provides an excellent set of tools for developing Web applications. In this article, you will learn how to use Django (http://djangoproject.com/) to develop a project called "Learning Notes" (Learning Log), an online logging system that allows you to record what you have learned about a particular topic.

We will develop a specification for this project and then define a model for the data used by the application. We will use Django's management system to enter some initial data, and then learn to write views and templates so that Django can create pages for our website. Django is a Web framework-a set of tools to help develop interactive websites. Django can respond to web requests and make it easier for you to read and write databases, manage users, and so on. In chapters 19 and 20, we will improve the Learning Notes project and deploy it to the active server so that you and your friends can use it.

First, establish a project

When you set up a project, you first need to describe the project in a standardized way, and then establish a virtual environment in which to create the project.

(1) to formulate norms

The complete specification details the objectives of the project, describes the functions of the project, and discusses the appearance and user interface of the project. As with any good project planning and business plan, the specification should be focused to help prevent the project from going off track. A complete project plan will not be developed here, but only some clear goals will be listed to highlight the focus of development. The specifications we have developed are as follows:

We are going to write a Web application called Learning Notes that allows users to record topics of interest and add log entries as they learn each topic. The home page of Learning Notes describes the site and invites users to sign up or log in. After the user logs in, you can create new topics, add new entries, and read existing entries. As you learn new topics, recording what you have learned can help you track and review that knowledge. Excellent applications make this recording process simple and easy.

(2) establishing a virtual environment

To use Django, you first need to establish a virtual work environment. A virtual environment is a location of the system where you can install packages and isolate them from other Python packages. It is useful to separate the project's library from other projects, and it is necessary to deploy the Learning Notes to the server in Chapter 20.

Create a new directory for the project, name it learning_log, change to this directory in the terminal, and create a virtual environment. If you are using Python3, you can create a virtual environment using the following command:

Here you run the module venv and use it to create a virtual environment called ll_env. If this works, skip to the next section 18.1.4; if it doesn't, read section 18.1.3.

(3) install virtualenv

If you are using an earlier version of Python, or if the system is not set up correctly, you cannot use the module venv, you can install the virtualenv package. To do this, you can execute the following command:

Pip3 install-user virtualenv

Don't forget that you may need to use a slightly different version of this command (if you haven't used pip, see Section 12.2.1).

Note that if you are using a Linux system and the above does not work, use the system's package manager to install virtualenv. For example, to install virtualenv on a Ubuntu system, use the command sudo apt-getinstall python-virtualenv.

Change to the directory learning_log in the terminal and create a virtual environment as follows:

Note that if you have more than one version of Python installed on your system, you need to specify the version that virtualenv uses. For example, the command virtualenv ll_env-- python=python3 creates a virtual environment using Python 3.

Win10 available

Python3-m virtualenv 11_env

To create

(4) activate the virtual environment

After you have established the virtual environment, you need to activate it using the following command:

This command runs the script activate in ll_env/bin. When the environment is active, the environment name is enclosed in parentheses, as shown at ❶. In this case, you can install the package in the environment and use the installed package. The packages you install in ll_env are only available when the environment is active.

Note that if you are using a Windows system, use the command ll_env\ Scripts\ activate (without source) to activate the virtual environment.

If you report an error, please use the full path.

E:\ science and technology innovation project\ djange framework\ learning_log\ 11_env\ Scripts\ activate

To stop using the virtual environment, execute the command deactivate:

E:\ science and technology innovation project\ djange framework\ learning_log\ 11_env\ Scripts\ deactivate

If you close the terminal running the virtual environment, the virtual environment will no longer be active.

(5) install Django

After creating and activating the virtual environment, you can install Django:

Because we work in a virtual environment, the command to install Django is the same on all systems: you don't need to specify the flag-- user, and you don't need to use a longer command like python-m pip install package_name.

Don't forget that Django is only available when the virtual environment is active.

(VI) create a project in Django

With the virtual environment still active (ll_env is enclosed in parentheses), execute the following command to create a new project:

Django-admin startproject learning_log.

The department's command tells Django to create a new project called learning_log. The period at the end of this command allows the new project to use the appropriate directory structure so that the application can be easily deployed to the server after development.

Be careful not to forget this period, or you will encounter some configuration problems when deploying the application. If you forget this period, delete the created files and folders (except ll_env) and rerun the command.

Note that the ls instruction cannot be used under windows. Use dir to view all the files in the directory.

The command ls (which should be dir on Windows systems) is run there, and it turns out that Django has created a new directory called learning_log. It also creates a file called manage.py, a simple program that accepts commands and gives it to the relevant parts of Django to run. We will use these commands to manage tasks such as working with the database and running the server.

The directory learning_log contains four files (see above), the most important of which are settings.py, urls.py, and wsgi.py. The file settings.py specifies how Django interacts with your system and how to manage the project. During the development of the project, we will modify some of these settings and add some settings. The file urls.py tells Django which web pages should be created in response to browser requests. The file wsgi.py helps Django provide the file it created, which is an acronym for web server gatewayinterface (Web Server Gateway Interface).

(7) create a database

Django stores most of the project-related information in a database, so we need to create a database for Django to use. To create a database for the project Learning Notes, execute the following command while in an active virtual environment:

Python3 manage.py migrate

The Django in the following figure indicates that it will create the necessary database tables to store the information we will use in this project (Synchronizeunmigrated apps, synchronizing unmigrated applications), and then ensure that the database structure matches the current code (Apply all migrations, apply all migrations).

We call a modified database a migration database. When the command migrate is executed for the first time, Django is asked to ensure that the database matches the current state of the project. The first time this command is executed in a new project that uses SQLite (described in more detail later), Django will create a new database.

In the command in the figure above, Django indicates that it will create the necessary database tables to store the information we will use in this project (Synchronizeunmigrated apps, synchronizing unmigrated applications), and then ensure that the database structure matches the current code (Apply all migrations, apply all migrations).

Next, we run the command dir, and its output shows that Django has created another file, db.sqlite3. SQLite is a database that uses a single file and is ideal for writing simple applications because it keeps you from paying too much attention to database management.

(8) View the project

Let's verify that Django created the project correctly. To do this, execute the command runserver, as follows:

Python3 manage.py runserver

Django starts a server that allows you to view projects in the system and see how they work. When you type URL into the browser to request a web page, the Django server will respond by generating the appropriate web page and sending it to the browser.

At ❶, Django confirms that the project is created correctly by checking; at ❷, it indicates the version of Django used and the name of the settings file currently in use; at ❸, it indicates the URL of the project. URL http://127.0.0.1:8000/ indicates that the project will listen for requests on port 8000 of your computer (that is, localhost). Localhost is a server that only processes requests from the current system and does not allow anyone else to view the web page you are developing.

Now open a Web browser and type URL: http://localhost:8000/; if this doesn't work, type http://127.0.0.1:8000/. You will see a page similar to the one shown below, which was created by Django to let you know that everything has been fine so far. Don't shut down the server for now. To shut down the server, press Ctrl+C.

Note that if there is an error message "That port is already in use" (the specified port is already occupied), execute the command python manage.pyrunserver 8001 to have Diango use another port; if this port is not available, continue to execute the above command and gradually increase the port number until an available port is found.

Give it a try.

18-1 New projects:

To learn more about what Django has done, create two empty projects to see what Django has created. Create a new folder and give it a simple name, such as InstaBook or FaceGram (do not create the folder in the directory learning_log), switch to that folder in the terminal, and create a virtual environment. Install Django in this virtual environment and execute the command django-admin.py startprojectinstabook. (don't forget the period at the end of the command).

See which files and folders are created by this command and compare them with the files and folders contained in the project Learning Notes. Do this a few more times until you know exactly what Django created when it created a new project. Then, delete the project directory-if you want to.

Create an application

The Django project consists of a series of applications that work together to make the project a whole. For the time being, we will only create one application, which will do most of the work of the project. In Chapter 19, we will add another application to manage user accounts.

Currently, runserver should still be running in the terminal window that opened earlier. Please open another terminal window (or tab) and change to the directory where manage.py is located. Activate the virtual environment, and then execute the command startapp:

Python3 manage.py startapp learning_logs

The command startapp appname lets Django build the infrastructure needed to create the application.

If you look at the project directory now, you will see a new folder, learning_logs (see ❶). Open this folder and see what Django has created (see ❷). The most important files are models.py, admin.py, and views.py. We will use models.py to define the data we want to manage in the application. Admin.py and views.py will be introduced later.

(I) define the model

Let's think about the data involved. Each user needs to create a number of topics in the study notes. Each entry entered by the user is associated with a specific topic, and the entries are displayed as text. We also need to store the timestamp of each entry so that we can tell the user when each entry was created.

Open the file models.py and see what it currently contains:

Models.py

This imports the module models for us and allows us to create our own model. The model tells Django how to handle the data stored in the application. At the code level, a model is a class that, like every class discussed earlier, contains properties and methods. The following is a model that represents the topic that the user will store:

From django.db import models# Create your models here.class Topic (models.Model): "" user learning topics "text = models.CharField (max_length=200) date_added = models.DateTimeField (auto_now_add=True) def _ _ str__ (self):" returns the string representation of the model "return self.text"

We created a class called Topic, which inherits a class from Model--Django that defines the basic functionality of the model. The Topic class has only two properties: text and date_added. The attribute text is a CharField-- consisting of characters or text (see ❶). Use CharField when you need to store a small amount of text, such as a name, title, or city. When defining the CharField property, you must tell Django how much space should be reserved in the database. Here, we set the max_length to 200 (that is, 200 characters), which is sufficient to store most topic names.

The property date_added is a DateTimeField-- that records data for the date and time (see ❷). We pass the argument auto_now_add=True, which causes Django to automatically set this property to the current date and time every time the user creates a new theme.

Note that to learn about the various fields that can be used in the model, see DjangoModel Field Reference (Django Model Field reference), which is available at https://docs.djangoproject.com/en/1.8/ref/models/fields/. For now, you don't need to know everything about it, but it can be of great help when you develop your own applications.

We need to tell Django which attribute should be used by default to display information about the topic. Django calls the method _ _ str__ () to display a simple representation of the model. Here, we write the method _ _ str__ (), which returns the string stored in the property text (see ❸).

Note that if you are using Python 2.7, you should call the method _ _ unicode__ () instead of _ _ str__ (), but the code is the same.

(2) activate the model

To use the model, you must have Django include the application in the project. To do this, open settings.py (which is in the directory learning_log/learning_log), and you will see a snippet that tells Django which applications are installed in the project:

Settings.py

INSTALLED_APPS = ['django.contrib.admin',' django.contrib.auth', 'django.contrib.contenttypes',' django.contrib.sessions', 'django.contrib.messages',' django.contrib.staticfiles',]

This is a tuple that tells Django which applications the project is made up of. Modify the INSTALLED_APPS as follows to add the previous application to this tuple:

INSTALLED_APPS = [--snip-- # omit the above code 'django.contrib.staticfiles', # my application' learning_logs',]

By grouping applications, it helps to track applications as the project grows and contains more applications. Here is a new snippet called Myapps, which currently contains only the application learning_logs. Next, you need to have Django modify the database so that it can store information related to the model Topic. To do this, execute the following command in the terminal window:

Python3 manage.py makemigrations learning_logs

Note:

If it appears

LookupError: No installed app with label 'admin'.

If an error is reported, it means that the format of the above settings.py file is incorrect.

The command makemigrations lets Django determine how to modify the database so that it can store the data associated with the new model we defined. The output shows that Django created a migration file called 0001_initial.py, which will create a table for the model Topic in the database.

Let's apply this migration and let Django modify the database for us:

Python3 manage.py migrate

Most of the output from this command is the same as the output from our first execution of the command migrate. What we need to check is the output line at ❶, where Django confirms that everything is fine when the learning_logs application is migrated (OK).

Whenever you need to modify the data managed by Learning Notes, take the following three steps: modify models.py; to learning_logs call makemigrations; to Django to migrate the project.

(3) Django management website

When defining a model for an application, the management website (adminsite) provided by Django makes it easy for you to work with the model. The administrator of the website can use to manage the website, but the average user cannot use it. In this section, we will set up an administrative Web site and use it to use the model Topic to add some themes.

1. Create a superuser

Django allows you to create users with all privileges-superusers. Permissions determine the actions that the user can perform. The strictest permission settings only allow users to read public information on the site; registered users can usually read their own private data and view information that only members can view. In order to effectively manage Web applications, site owners usually need to access all the information stored on the site. Good administrators are careful with users' sensitive information because users have a great deal of trust in the applications they access.

To create a superuser in Django, execute the following command and follow the prompts:

Python3 manage.py createsuperuser

When you execute the command createsuperuser, Django prompts you to enter the user name of the superuser (see ❶). Here we enter ll_admin, but you can enter any user name, such as an e-mail address, or leave this field blank (see ❷). You need to enter your password twice (see ❸).

Note that some sensitive information may be hidden from the webmaster. For example, Django does not store the password you enter, but a string derived from that password, the hash value. Every time you enter a password, Django calculates its hash and compares the result with the stored hash. If the two hash values are the same, the authentication is passed. By storing the hash value, even if the hacker gets access to the website database, he can only get the hash value stored in it, but not the password. When the site is configured correctly, it is almost impossible to derive the original password from the hash value.

2. Register the model with the management website

Django automatically adds some models to the administration site, such as User and Group, but for the models we create, we have to register them manually.

When we created the application learning_logs, Django created a file called admin.py in the same directory as models.py:

Admin.py

From django.contrib import admin# Register your models here.from learning_logs.models import Topicadmin.site.register (Topic)

This code is imported into the model we want to register, Topic (see ❶), and then use admin.site.register () (see ❷) to let Django manage our model through the administrative website.

Now, use the superuser account to access the admin website: visit http://localhost:8000/admin/ and enter the username and password of the superuser you just created, and you will see a screen similar to the one shown below. This page allows you to add and modify users and user groups, and to manage data related to the model Topic just defined.

Note that if you see a message in your browser indicating that the web page you visited is not available, please make sure that you are running the Django server in the terminal window. If not, activate the virtual environment and execute the command python manage.py runserver.

3. Add a theme

After registering Topic with the admin website, let's add the first theme. To do this, click Topics to go to the theme page, which is almost empty because we haven't added any themes yet. Click Add and you will see a form for adding a new theme. Enter Chess in the first box, and then click Save, which returns you to the theme management page, which contains the theme you just created. Let's create another theme so that more data is available. Click Add again and create another theme, Rock Climbing. When you click Save, you will return to the theme management page, which contains the themes Chess and RockClimbing.

(4) define the model Entry

To record what you have learned about chess and rock climbing, you need to define a model for the items that users can add to their study notes. Each entry is associated with a specific topic, which is called a many-to-one relationship, that is, multiple entries can be associated with the same topic.

Here is the code for the model Entry:

Models.py

From django.db import modelsclass Topic (models. Model):-- snip--class Entry (models.Model): specific knowledge learned by ➊ "topic = models.ForeignKey (Topic) ❷ text = models.TextField () ❸ date_added = models.DateTimeField (auto_now_add=True) class Meta: ❹ verbose_name_plural = 'entries' def" _ _ str__ (self): "returns the string representation of the model"return self.text [: 50] +"... "❺

Like Topic, Entry inherits the Django base class Model (see ❶). The first property topic is an instance of ForeignKey (see ❷). A foreign key is a database term that refers to another record in the database; the code associates each entry to a specific topic. When each topic is created, it is assigned a key (or ID). When you need to establish a connection between two pieces of data, Django uses the key associated with each piece of information. Later we will get all the entries associated with a particular topic based on these connections.

Next is the property text, which is an instance of TextField (see ❸). This field does not require a length limit because we do not want to limit the length of the entry. The attribute date_added allows us to render entries in the order in which they are created and place a timestamp next to each entry.

At ❹, we nest the Meta class in the Entry class. Meta stores additional information for managing the model, and here it allows us to set a special property that allows Django to use Entries to represent multiple entries as needed. Without this class, Django will use Entrys to represent multiple entries. Finally, the method _ _ str__ () tells Django what information should be displayed when the entry is rendered. Because the entry may contain long text, we asked Django to display only the first 50 characters of the text (see ❺). We also added an ellipsis to indicate that the entire entry is not displayed.

(5) Migration Model Entry

Because we have added a new model, we need to migrate the database again. You will slowly know the process like the back of your hand:

Modify models.py, execute command

Python manage.py makemigrations app_name

An error is reported.

TypeError: _ _ init__ () missing 1 required positional argument: 'on_delete'

Solution:

You need to add on_delete= when defining foreign keys

That is: contract = models.ForeignKey (Contract, on_delete=models.CASCADE)

The reasons are as follows:

After django is upgraded to 2.0, when the table is associated with each other, the on_delete parameter must be written, otherwise an exception will be reported:

TypeError: init () missing 1 required positional argument: 'on_delete'

The parameters of on_delete are as follows:

On_delete=None, # behavior of the field associated with the current table when deleting data from the associated table

On_delete=models.CASCADE, # delete associated data, and associated with it also delete

On_delete=models.DO_NOTHING, # delete the associated data and do nothing

On_delete=models.PROTECT, # Delete the associated data, causing an error ProtectedError

# models.ForeignKey ('Association Table', on_delete=models.SET_NULL, blank=True, null=True)

On_delete=models.SET_NULL, # Delete the associated data and set the associated value to null (provided that the FK field needs to be set to nullable, one-to-one)

# models.ForeignKey ('Associated Table', on_delete=models.SET_DEFAULT, default=' default')

On_delete=models.SET_DEFAULT, # Delete the associated data and set the value associated with it to the default value (provided that the FK field needs to be set to the default value, one-to-one)

On_delete=models.SET, # Delete associated data

a. The value associated with it is set to the specified value, setting: models.SET (value)

b. The value associated with it is set to the return value of the executable object, setting: models.SET (executable object)

After modification, the command is executed successfully.

Python3 manage.py migrate

Let's migrate the database and view the output:

A new migration file, 0002_entry.py, is generated, which tells Django how to modify the database so that it can store information related to the model Entry (see ❶). By executing the command migrate, we found that Django applied this migration and everything went well (see ❷).

(6) register Entry with the management website

We also need to register the model Entry. To do this, you need to modify the admin.py to look like this:

From django.contrib import adminfrom learning_logs.models import Topic,Entryadmin.site.register (Topic) admin.site.register (Entry)

Return to http://localhost:8000/admin/ and you will see that Entries is listed under learning_logs. Click the Add link for Entries, or click Entries and then select Add entry. You will see a drop-down list that allows you to choose which topic you want to create an item for, as well as a text box for entering items. Select Chess from the drop-down list and add an entry. Here is the first entry I added.

The opening is thefirst part of the game, roughly thefirst ten moves or so. In the opening, it's a good ideato do three things- bring out your bishops andknights, try to control the center of the board, andcastle your king. (the first stage of chess is the beginning, roughly the first 10 steps. In the opening stage, it is best to do three things: bring out the elephant and the horse; try to control the middle area of the chessboard; and protect the king with the car. ) Of course, these are just guidelines. It will beimportant to learn when to follow these guidelinesand when to disregard these suggestions. (these are just guiding principles, of course. It is important to learn when to abide by these principles and when not to. )

When you click Save, you will return to the main item management page. Here, you'll find the advantage of using text [: 50] as a string representation of an item: in the administrative interface, only the beginning of the item is displayed instead of all its text, which makes it much easier to manage multiple items.

Let's create a chess entry and a rock climbing entry to provide some initial data. Here is the second chess entry.

In the opening phase of the game, it's important tobring out your bishops and knights. At the beginning of chess, it is important to These pieces arepowerful and maneuverable enough to play asignificant role in the beginning moves of a game the elephant and the horse. These pieces are powerful and mobile, and play an important role in the opening stage. )

Here is the first climbing entry:

One of the most important concepts in climbing is tokeep your weight on your feet as much as possible.There's a myth that climbers can hang all day on theirarms. In reality, good climbers have practiced specificways of keeping their weight over their feet wheneverpossible. (one of the most important climbing concepts is to make your feet bear the weight as much as possible. There is a fallacy that climbers can rely on the strength of their arms for a whole day. In fact, good climbers are specially trained to bear the weight on their feet as much as possible. )

As we continue to develop Learning Notes, these three entries can provide us with the data we use.

(7) Django shell

After entering some data, you can view the data programmatically through an interactive terminal session. This interactive environment, called Django shell, is an ideal place to test projects and troubleshoot them. Here is an example of an interactive shell session:

Python3 manage.py shellfrom learning_logs.models import TopicTopic.objects.all ()

When executed in an active virtual environment, the command python manage.py shell launches a Python interpreter that you can use to explore the data stored in the project database. Here, we import the model Topic from the module learning_logs.models (see ❶), and then use the method Topic.objects.all () to get all instances of the model Topic; it returns a list called the query set (queryset).

We can traverse the query set as if it were a list. The following demonstrates how to view the ID assigned to each topic object:

Topics = Topic.objects.all () for topic in topics: print (topic.id,topic)

We store the returned query set in topics, and then print the id property and string representation for each topic. As you can see from the output, the ID of the theme Chess is 1, while the ID of RockClimbing is 2.

Once you know the ID of an object, you can get the object and view any of its properties. Let's take a look at the values of the properties text and date_added of the theme Chess:

T = Topic.objects.get (id=1) t.textt.date_added

We can also view the entries associated with the topic. Earlier, we defined the property topic for the model Entry, which is a ForeignKey that associates items with topics. With this association, Django can get all the entries associated with a particular topic, as follows:

T.entry_set.all ()

To get data through foreign key relationships, use the lowercase name, underscore, and word set of the related model (see ❶). For example, suppose you have models Pizza and Topping, and Topping is associated with Pizza; through a foreign key. If you have an object named my_pizza that represents a pizza, you can use the code my_pizza.topping_set.all () to get all the ingredients of the pizza.

We will use this syntax when writing web pages that users can request. Shell is helpful when confirming that the code can get the data you need. If the code behaves as expected in shell, it will also work correctly in the project file. If the code causes an error or the data obtained is not as expected, it is much easier to troubleshoot in a simple shell environment than in a file that generates a web page. We won't use shell too much, but we should continue to use it to familiarize ourselves with the Django syntax for accessing data stored in the project.

Note that every time you modify the model, you need to restart shell so that you can see the effect of the changes. To exit the shell session, press Ctr+D;. If you are using a Windows system, press Ctr+Z and press enter.

Give it a try.

18-2 short entries:

Currently, when Django displays Entry instances in an administrative Web site or shell, the model Entry method _ _ str__ () adds an ellipsis at the end of it. Add an if statement to the method _ _ str__ () to add an ellipsis only if the length of the entry exceeds 50 characters. Use the admin site to add an entry that is less than 50 characters long and verify that it is displayed without an ellipsis.

18-3 Django API:

When you write code that accesses the data in the project, you write queries. Browse to the documentation on how to query the data at https://docs.djangoproject.com/en/7.8/topics/db/queries/. Most of the content is unfamiliar to you, but it will be useful when you develop your own projects.

18-4 pizza parlor:

Create a new project called pizzeria and add an application named pizzas to it. Define a model called Pizza, which contains fields name to store pizza names, such as Hawaiian and Meat Lovers. Define a model called Topping, which contains fields pizza and name, where field pizza is a foreign key associated with Pizza, and field name is used to store ingredients such as pineapple, Canadianbacon, and sausage.

Register the two models with the admin website and use the admin website to enter some pizza names and ingredients. Use shell to view the data you enter.

Third, create a web page:

The process of creating a web page using Django on the learning notes home page is usually divided into three stages: defining the URL, writing views, and writing templates. First, you must define the URL schema. The URL pattern describes how URL is designed to let Django know how to match browser requests to the site's URL to determine which page to return.

Each URL is mapped to a specific view-- the view function acquires and processes the data needed for the web page. The view function usually calls a template that generates a web page that the browser can understand. To understand how it works, let's create a home page for learning notes. We will define the URL of the home page, write its view function, and create a simple template.

Since we just want to make sure that Learning Notes works as required, we will make this page as simple as possible for the time being. After the Web application is working properly, styling can make it more interesting, but useless applications are meaningless. For now, the home page displays only the title and a simple description.

(1) Mapping URL

The user requests a web page by entering URL in the browser and clicking the link, so we need to determine which URL is needed for the project. The URL of the home page is the most important, and it is the basic URL that users use to access the project. Currently, the base URL (http://localhost:8000/) returns the default Django site to let us know that the project has been set up correctly. We will modify this to map this basic URL to the home page of Learning Notes.

Open the file urls.py in the project's home folder learning_log, and you will see the following code:

From django.contrib import admin ❶ from django.urls import pathurlpatterns = [❷ path ('admin/', admin.site.urls), ❸]

The first two lines import the functions and modules for managing URL for the project and management Web site (see ❶). The body of this file defines the variable urlpatterns (see ❷). In this urls.py file for the entire project, the variable urlpatterns contains the URL of the application in the project. The code at ❸ contains the module admin.site.urls, which defines all the URL that can be requested in the administrative Web site.

We need a URL that contains learning_logs:

Original code

From django.contrib import adminfrom django.urls import pathurlpatterns = [path ('admin/', admin.site.urls),]

After modification

From django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [url (r'^ admin/',include (admin.site.urls)), url (ringing eggs, include ('learning_logs.urls',namespace='learning_logs')), ➊]

At ❶, we added a line of code to include the module learning_logs.urls. This line of code contains the argument namespace, which allows us to distinguish the URL of learning_logs from other URL in the project, which is helpful when the project starts to expand.

The default urls.py is contained in the folder learning_log, so now we need to create another urls.py file in the folder learning_logs:

"" defines the URL schema for learning_ logs "" ➊ from django.conf.urls import url ❷ from. " Import views ❸ urlpatterns = [❹ # homepage url (r'^ $', views.index, name='index'), ❺]

To find out which urls.py file you are currently in, we added a document string at the beginning of the file (see ❶). Next, we imported the function url, because we need to use it to map the URL to the view (see ❷). We also imported the module views (see ❸), where the period lets Python import views from the same folder as the current urls.py module. In this module, the variable urlpatterns is a list of web pages that can be requested in the application learning_logs (see ❹).

The actual URL pattern is a call to the function url (), which accepts three arguments (see ❺). The first is a regular expression. Django looks in urlpatterns for regular expressions that match the requested URL string, so regular expressions define patterns that Django can find.

Let's take a look at the regular expression r'^ $'. The r tells Python to treat the following string as the original string, while quotation marks tell Python where the regular expression begins and ends. Delimiting (^) lets Python look at the beginning of the string, while the dollar sign lets Python see the end of the string. In general, this regular expression lets Python look for URL with nothing between the beginning and the end. Python ignores the project's underlying URL (http://localhost:8000/), so this regular expression matches the underlying URL. None of the other URL matches this regular expression. If the requested URL does not match any URL patterns, Django returns an error page.

The second argument to url () (see ❺) specifies the view function to be called. When the requested URL matches the previous regular expression, Django will call views.index (this view function will be written in the next section). The third argument specifies the name of the URL schema as index, allowing us to reference it elsewhere in the code. Whenever we need to provide a link to this home page, we will use this name instead of writing URL.

Note:

The above tutorial is Django1.11

Writing in urls.py is not supported after django2.0

Url (r'^ admin/', include (admin.site.urls))

An error will occur after runserver

, use directly

Path ('admin/', admin.site.urls)

You still need to use include () for references to custom urls.py files in the application

Baidu got a way to improve at once.

The first step is to modify learning_log\ urls.py

From django.contrib import admin# from django.conf.urls import include, urlfrom django.urls import path,includeurlpatterns = [path ('admin/', admin.site.urls), path (', include ('learning_logs.urls', namespace='learning_logs')), # url (r' ^ admin/', include (admin.site.urls)), # url (rushing, include ('learning_logs.urls', namespace='learning_logs')), Django2.0 uses django.urls.path]

However, only adding namespace will result in an error. The variable app_name must be defined in learning_logs\ urls.py.

Learning_logs\ urls.py

From django.urls import path, include, re_pathfrom. Import viewsurlpatterns = [# url (r'^ $', views.index, name='index'), re_path ('^ $', views.index, name='index')] app_name = 'learning_logs'

Then run runserver and there will be no mistakes.

Note that regular expressions are often called regex and are used in almost every programming language. They have an incredible variety of uses, but it takes some practice to get familiar with them. If you don't understand the previous introduction, don't worry, you will see a lot of regular expressions as you complete the project.

(2) compiling views

The view function accepts the information in the request, prepares the data needed to generate the web page, and sends it to the browser-- usually using a template that defines what the web page is.

The file views.py in learning_logs is automatically generated when you execute the command python manage.py startapp, which currently contains the following:

Currently, this file imports only the function render (), which renders the response based on the data provided by the view. The following code demonstrates how to write a view for the home page:

From django.shortcuts import renderdef index (request): "" homepage of study notes "" return render (request,'learning_logs/index.html') "

When the URL request matches the pattern we just defined, Django will look for the function index () in the file views.py and pass the request object to the view function. Here, we don't need to process any data, so this function only contains the code that calls render (). The function render () is provided with two arguments: the original request object and a template that can be used to create a web page. Let's write this template.

18.3.3 Writing templates

The template defines the structure of the web page. The template specifies what the page looks like, and every time the page is requested, Django will fill in the relevant data. Templates give you access to any data provided by the view. Our home page view does not provide any data, so the corresponding template is very simple.

Create a new folder in the folder learning_logs and name it templates. In the folder templates, create a new folder and name it learning_logs. This seems a bit redundant (we created the folder templates in the folder learning_logs and the folder learning_logs in this folder), but it establishes a structure that Django can clearly interpret, even if the project is large and contains a lot of applications. In the innermost folder learning_logs, create a new file, name it index.html, and write the following code in this file:

Learning Log

Learning Log helps you keep track of your learning, for any topic you're learning about.

This file is very simple. For readers who are not familiar with HTML, here's an explanation:

Label

To identify a paragraph; label.

Indicates the beginning of the paragraph, while the tag

The end of the paragraph is pointed out. Two paragraphs are defined here: the first serves as the title and the second describes what users can do with Learning Notes.

Now, if you request the basic URL-- http://localhost:8000/ for this project, you will see the page you just created instead of the default Django page. Django accepts the requested URL and finds that the URL matches the pattern r'^ $', so it calls the function views.index (), which renders the web page using the template contained in index.html, as shown in the following figure.

The process of creating a web page may seem complicated, but the separation of URL, view, and template actually works well. This allows us to consider different aspects of the project separately and allows participants to focus on what they are best at when the project is large. For example, database experts can focus on models, programmers can focus on view code, and Web designers can focus on templates.

Try the 18-5 meal planning process:

Suppose you want to create an application to help users plan their meals for a week. To do this, create a new folder and name it meal_planner, and then create a new Django project in this folder. Next, create a new application called meal_plans and create a simple home page for the project.

18-6 Pizzeria home page:

In the project Pizzeria that you created to complete exercise 18-4, add a home page.

Fourth, create other web pages

Once you have established the process for creating a web page, you can begin to expand the Learning Notes project. We will create two web pages that display data, one of which lists all the topics and the other shows all the entries for a particular topic. For each page, we will specify the URL mode, write a view function, and write a template. But before we do that, let's create a parent template that all other templates in the project will inherit.

(1) template inheritance

When you create a Web site, there are elements that almost all pages will contain. In this case, you can write a parent template that contains common elements and have each page inherit the template without having to define these common elements repeatedly in each page. This approach allows you to focus on the unique aspects of each page and makes it much easier to modify the overall appearance of the project.

1. Parent template

Let's first create a template called base.html and store it in the same directory as index.html. This file contains elements that all pages have; all other templates inherit base.html. Currently, all pages contain only the top title. We will include this template in each page, so we set the title to the link to the home page:

Learning Log ➊

{% block content%} {% endblock content%} ❷

The first part of this file creates a paragraph containing the project name, which is also a link to the home page. To create the link, we used a template tag that is represented by curly braces and a percent sign ({%}). A template tag is a small piece of code that generates information to be displayed on a web page. In this example, the template tag {% url 'learning_logs:index'%} generates a URL that matches the URL pattern named index defined in learning_logs/urls.py (see ❶). In this example, learning_logs is a namespace, and index is a uniquely named URL schema in that namespace.

In a simple HTML page, links are defined using anchor tags:

Link text

It is much easier to keep links up-to-date by using template tags to generate URL. To modify the URL in the project, simply modify the URL mode in the urls.py so that when the page is requested, the Django will automatically insert the modified URL. In our project, every web page will inherit base.html, so from now on, every web page contains a link to the home page.

At ❶, we insert a pair of block tags. The block, named content, is a placeholder and the information it contains will be specified by the subtemplate.

The child template does not have to define each block in the parent template, so you can use as many blocks as you want to reserve space in the parent template, and the child template can define the appropriate number of blocks as needed.

Notice that in the Python code, we almost always indent four spaces. Template files have more indentation levels than Python files, so each level is usually indented by only two spaces.

2. Subtemplate

Now you need to rewrite index.html to inherit base.html, as follows:

{extends "learning_logs/base.html"%} ➊ {% block content%} ❷

Learning Log helps you keep track of your learning, for any topic you're learning about.

{% endblock content%} ❸

If you compare this code with the original index.html, you can see that we replaced the title Learning Log with the code inherited from the parent template (see ❶). The first line of the child template must contain the label {% extends%} to let Django know which parent template it inherits. The file base.html is in the folder learning_logs, so the parent template path contains learning_logs. This line of code imports all the contents of the template base.html, allowing index.html to specify what to add in the space reserved for the content block.

At ❷, we insert a {% block%} tag named content to define the content block. Everything that is not inherited from the parent template is contained in the content block, which is a paragraph that describes the project's "learning notes". At ❸, we use the label {% endblock content%} to indicate the end of the content definition.

The advantages of template inheritance are beginning to show: in subtemplates, you only need to include content specific to the current web page. This not only simplifies each template, but also makes the site much easier to modify. To modify the element that many pages contain, simply modify the element in the parent template, and your changes will be transmitted to each page that inherits the parent template. In projects with dozens or even hundreds of pages, this structure makes site improvement much easier and much faster.

Note that in large projects, there is usually a parent template for the entire site, base.html, and each major part of the site has a parent template. The parent template of each section inherits base.html, while each page of the site inherits the parent template of the corresponding section. This allows you to easily modify the appearance of the entire site, the appearance of any part of the site, and the appearance of any page. This configuration provides an extremely efficient way to work, so that you are willing to constantly improve the site.

(II) pages that display all topics

With an efficient method of creating web pages, you can focus on the other two pages: pages that display all themes and pages that display items in a particular topic. All theme pages show all the themes created by the user, and it is the first web page that needs to use data.

1.URL mode

First, let's define the URL of the page that displays all the topics. Typically, a simple URL snippet is used to indicate the information displayed on a web page; we will use the word topics, so URL http://localhost:8000/topics/ will return a page that shows all the topics. The following shows how to modify learning_logs/urls.py:

"" defines the URL schema for learning_ logs "" from django.urls import path, include, re_pathfrom. " Import viewsurlpatterns = [# homepage # url (r'^ $', views.index, name='index'), re_path ('^ $', views.index, name='index'), # url (r'^ topics/$',views.topics,name='topics'), path ('topics/',views.topics,name='topics'), ❶] app_name =' learning_logs'

We just added topics/ to the regular expression for the home page URL (see ❶). When Django checks the requested URL, this pattern matches the URL where the underlying URL is followed by topics. You can include a slash at the end, or you can omit it, but there cannot be anything after the word topics, otherwise it will not match the pattern. Requests whose URL matches the pattern are passed to the function topics () in views.py for processing.

2. View

The function topics () needs to take some data from the database and send it to the template. The code we need to add to views.py is as follows:

From django.shortcuts import renderfrom .models import Topic ➊ def index (request):-- snip--def topics (request): ❷ "" shows all topics "" topics = Topic.objects.order_by ('date_added') ❸ context = {' topics': topics} ❹ return render (request,'learning_logs/topics.html', context) ❺ "

We first imported the model associated with the required data (see ❶). The function topics () contains a formal parameter: the request object that Django receives from the server (see ❷). At ❸, we query the database-- request Topic objects and sort them by property date_added. We store the returned query set in topics.

At ❹, we define a context that will be sent to the template. The context is a dictionary in which the key is the name that we will use to access the data in the template, and the value is the data we want to send to the template. Here, there is only one key-value pair, which contains a set of topics that we will display on the page. When creating a Web page that uses data, in addition to the path to the object request and template, we pass the variable context to render () (see ❺).

3. Template

The template that displays the page for all topics accepts the dictionary context so that the data provided by topics () can be used. Create a file, name it topics.html, and store it in the same directory as index.html. The following demonstrates how to display the theme in this template:

{% extends "learning_logs/base.html"} {% block content%}

Topics

➊ {% for topic in topics%} ❷ {{topic}} ❸ {% empty%} ❹ No topics have been added yet. {% endfor%} ❺❻ {% endblock content%}

Just like the template index.html, we first inherit the base.html using the label {% extends%}, and then start defining the content block. The main body of this page is a list of projects that list the topics entered by the user. In standard HTML, project lists are called unordered lists and are represented by tags. The list of projects with all topics starts at ❶.

At ❷, we use a template tag equivalent to a for loop, which iterates through the list topics in the dictionary context. There are some important differences between the code used in the template and the Python code: Python uses indentation to indicate which lines of code are part of the for loop, while in the template, each for loop must use the {% endfor%} tag to explicitly indicate where it ends. So in the template, the loop looks like this:

{foritem in list} do something with each item {endfor}

In the loop, we convert each topic to a project list item. To print a variable in a template, you need to enclose the variable name in double curly braces. At each loop, the code {{topic}} at ❸ is replaced with the current value of topic. These curly braces do not appear on the page, they are just used to tell Django that we are using a template variable. The HTML tag represents an item list item, and the content inside, between and between the tag pair is an item list item.

At ❹, we use the template label {% empty%}, which tells Django what to do if the list topics is empty: here is to print a message telling the user that no topics have been added. The last two lines end the for loop (see ❺) and the project list (see ❻).

Now you need to modify the parent template to include a link to the page that displays all topics:

We added a hyphen (see ❶) after the link to the home page, and then a link to the page showing all the topics-- also using the template tag url (see ❷). This line causes Django to generate a link that matches the URL pattern named topics in learning_logs/ urls.py.

Now if you refresh the home page in your browser, you will see the link Topics. Click this link and you will see a web page similar to the one shown in figure 18-4.

(3) pages that display specific topics

Next, we need to create a page that focuses on a specific topic-- showing the name of the topic and all the entries for the topic. Again, we will define a new URL schema, write a view, and create a template. We will also modify the page that displays all topics so that each item list item is a link, and clicking it will display all entries for the corresponding topic.

1.URL mode

The URL mode of a page that displays a specific topic is slightly different from all previous URL modes because it uses the theme's id property to indicate which topic is being requested. For example, if the user wants to view a detailed page of the theme Chess (whose id is 1), URL will be http://localhost:8000/topics/1/. Here is the pattern that matches this URL, which is included in the learning_logs/urls.py:

Django1.11 reform

Django2.0 reform:

Let's take a closer look at the regular expression in this URL pattern-- r'^ topics/ (? P\ d +) / $'. R asks Django to treat the string as the original string and indicates that the regular expression is enclosed in quotation marks. The second part of the expression (/ (? P\ d +) /) matches the integer contained in the two slashes and stores the integer in an argument named topic_id. The parentheses on both sides of this part of the expression capture the value in the URL;? P stores the matching value in the topic_id; and the expression\ d + matches any number contained in the two slants, no matter how many digits it is.

When URL is found to match this pattern, Django calls the view function topic () and passes it the value stored in topic_id as an argument. In this function, we will use the value of topic_id to get the corresponding theme.

2. View

The function topic () needs to get the specified topic and all the entries associated with it from the database, as shown below:

Views.py

-- snip--def topic (request,topic_id): ➊ "" displays a single topic and all its entries "topic = Topic.objects.get (id=topic_id) ❷ entries = topic.entry_set." Order_by ('- date_added') ❸ context = {'topic': topic,' entries': entries} ❹ return render (request,'learning_logs/topic.html', context) ❺

This is the first view function that contains another parameter in addition to the request object. This function takes the value captured by the regular expression (? P\ d +) and stores it in topic_id (see ❶). At ❷, we use get () to get the specified theme, as we did earlier in Django shell. At ❸, we get the entries associated with the topic and sort them by date_added: the minus sign before date_added specifies that they are sorted in descending order, that is, the most recent entries are displayed first. We store the topics and entries in the dictionary context (see ❹), which is then sent to the template topic.html (see ❺).

Note that the code at ❷ and ❸ is called a query because they query the database for specific information. When writing such a query in your own project, it is helpful to try it in Django shell first. Executing code in shell can get feedback faster than writing views and templates and then checking the results in a browser.

3. Template

This template needs to display the name of the topic and the contents of the entry; if the current topic does not contain any entries, we also need to point this out to the user:

Topic.html

{extends' learning_logs/base.html'%} {% block content%}

Topic: {{topic}}

Entries:

❷ {% for entry in entries%} ❸

{{entry.date_added | date:'M d, Y Hpuri'}}

{{entry.text | linebreaks}}

❺ {% empty%} ❻ There are no entries for this topic yet. {endfor} {endblock content}

Like other pages of this project, base.html is inherited here. Next, we show the current theme (see ❶), which is stored in the template variable {{topic}}. Why can you use the variable topic? Because it is included in the dictionary context. Next, we begin to define a list of projects that displays each entry (see ❷) and iterate through the entries as we did for all topics shown earlier (see ❸).

Each item list item lists two pieces of information: the timestamp of the entry and the complete text. To list the timestamp (see ❹), we display the value of the property date_added. In the Django template, the vertical bar (|) represents the template filter-a function that modifies the value of the template variable. The filter date:'Md, Y Hpuri 'displays the timestamp in this format: January 1, 2015 23:00. The next line shows the full value of text, not just the first 50 characters of entry. The filter linebreaks (see ❺) converts long entries containing newline characters into a format that the browser can understand so as not to appear as an uninterrupted block of text. At ❻, we use the template label {% empty%} to print a message telling the user that there is no entry for the current topic.

4. Set each topic on the page that displays all topics as a link

Before viewing a page that displays a specific theme in the browser, we need to modify the template topics.html so that each theme is linked to the appropriate web page, as shown below:

Snip-- {% for topic in topics%} {{topic}} {% empty%}-- snip--

We use the template tag url to generate the appropriate links based on the URL schema named topic in learning_logs. This URL mode requires that the argument topic_id be provided, so we added the attribute topic.id to the template tag url. Now each topic in the topic list is a link to a page that displays the topic, such as http://localhost:8000/topics/1/.

If you refresh a page that displays all themes, and then click one of the themes, you will see a page similar to the one shown below.

Give it a try.

18-8 pizza parlor page:

Add a page to the project Pizzeria developed in exercise 18-6 that displays the name of the supplied pizza. Then, set each pizza name to a link, and clicking this link will display a page listing the ingredients for the corresponding pizza. Be sure to use template inheritance to create pages efficiently.

On the Django3.0-based web framework detailed architecture process is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report