AI智能
改变未来

django 创建视图_如何为Django Web开发创建视图

django 创建视图

介绍 (Introduction)

If you’ve followed along with our Django Development series, you’ve successfully created a Django application that allows users with admin privileges to add comments and posts via Django’s admin UI dashboard. You’ve also set up data persistence by leveraging MySQL and Django’s object-relational mapping solution models.

如果您遵循我们的Django开发系列,那么您已经成功创建了Django应用程序,该应用程序允许具有管理员权限的用户通过Django的管理UI仪表板添加评论帖子 。 您还通过利用MySQL和Django的对象关系映射解决方案模型来设置数据持久性。

In this tutorial, we will create Django views that enable our web application to properly handle web requests and return the required web responses. As defined in the Django docs, a web response can be the HTML content of a Web page, a redirect, or an HTTP error (e.g.

404

). The code for the view functions can technically live anywhere in your project, as long as it’s on your Python path. However, there are some popular conventions for naming and placing the file in which these view functions exist, and we will be following these practices.

在本教程中,我们将创建Django 视图 ,使我们的Web应用程序能够正确处理Web请求并返回所需的Web响应。 如Django文档中所定义,网络响应可以是网页HTML内容,重定向或HTTP错误(例如

404

)。 从技术上讲,只要在Python路径上,视图函数的代码就可以存在于项目中的任何位置。 但是,存在一些流行的约定来命名和放置存在这些视图功能的文件,我们将遵循这些做法。

Once you are finished going through the steps of this tutorial, your Django blog site will pull a recent post into the

your-IP-or-domain/post

URL.

完成本教程的步骤后,您的Django博客站点会将最新的帖子拉到

your-IP-or-domain/post

URL中。

先决条件 (Prerequisites)

This tutorial is part of the Django Development series and is a continuation of that series.

本教程是Django开发系列的一部分,并且是该系列的继续。

If you have not followed along with this series, we are making the following assumptions:

如果您未遵循本系列文章,我们将进行以下假设:

  • You have Django version 3 or higher installed.

    您已安装Django版本3或更高版本。

  • You have connected your Django app to a database. We are using MySQL, and you can achieve this connection by following part two of the Django series, “How To Create a Django App and Connect it to a Database.”

    您已将Django应用程序连接到数据库。 我们正在使用MySQL,您可以通过遵循Django系列的第二部分“ 如何创建Django应用并将其连接到数据库 ”来实现此连接。

  • You are working with a Unix-based operating system, preferably an Ubuntu 20.04 cloud server as this is the system we have tested on. If you would like to set up Django on a similar environment, please refer to our tutorial, “How To Install Django and Set Up a Development Environment on Ubuntu 20.04.

    您正在使用基于Unix的操作系统,最好是Ubuntu 20.04云服务器,因为这是我们经过测试的系统。 如果您想在类似的环境中设置Django,请参考我们的教程“ 如何在Ubuntu 20.04上安装Django和设置开发环境” 。

  • You have set up your Django Admin Interface. You can accomplish this by following our Django Admin tutorial.

    您已经设置了Django Admin Interface。 您可以按照Django Admin教程来完成此操作。

As this guide is primarily dealing with Django Views, you may be able to follow along even if you have a somewhat different setup.

由于本指南主要涉及Django视图,因此即使设置有所不同,您也可以继续学习。

第1步-创建视图函数 (Step 1 — Create View Functions)

Within your terminal, you first need to move into the relevant directory and activate your Python virtual environment. If you have been following along with this series, you can enter the commands below. It is important to always use a Python programming environment when you are developing your app to ensure that your code is contained and you are working with the right setup.

在终端中,首先需要进入相关目录并激活Python虚拟环境。 如果您一直遵循本系列文章,则可以输入以下命令。 在开发应用程序时始终使用Python编程环境非常重要,以确保代码已包含并且使用正确的设置。

  • cd ~/my_blog_app

    cd〜/ my_blog_app

  • . env/bin/activate

    。 env / bin / activate

Now that your virtual environment is activated, let’s navigate to the

blogsite

directory where we will open up a Python file and create our first view function.

现在您的虚拟环境已激活,让我们导航到

blogsite

目录,我们将在其中打开Python文件并创建我们的第一个视图函数 。

  • cd ~/my_blog_app/blog/blogsite

    cd〜/ my_blog_app / blog / blogsite

Open the

views.py

file for editing, using nano or the text editor of your choice.

使用nano或您选择的文本编辑器打开

views.py

文件进行编辑。

  • nano views.py

    纳米views.py

Upon opening the file, it should be populated with code similar to this:

打开文件后,应使用类似于以下内容的代码填充该文件:

/my_blog_app/blog/blogsite/views.py /my_blog_app/blog/blogsite/views.py

from django.shortcuts import render# Create your views here.

We will keep the import statement that imports the

render()

function from the

django.shortcuts

library. The

render()

function allows us to combine both a template and a context so that we can return the appropriate

HttpResponse

object. Keep this in mind because with every view we write, we are responsible for instantiating, populating, and returning an

HttpResponse

.

我们将保留从

django.shortcuts

库导入

render()

函数的import语句 。

render()

函数允许我们将模板和上下文结合在一起,以便我们可以返回适当的

HttpResponse

对象。 请记住这一点,因为在我们编写的每个视图中,我们都负责实例化,填充和返回

HttpResponse

Next we’ll add our first view that will welcome users to the index page. We’ll import the

HttpResponse()

function from the Django

http

library. Using that function, we’ll pass in text to be displayed when the webpage is requested.

接下来,我们将添加第一个视图,该视图将欢迎用户进入索引页面。 我们将从Django

http

库中导入

HttpResponse()

函数。 使用该功能,我们将传递在请求网页时显示的文本。

~/my_blog_app/blog/blogsite/views.py 〜/ my_blog_app / blog / blogsite / views.py

from django.shortcuts import renderfrom django.http import HttpResponsedef index(request):return HttpResponse(\'Hello, welcome to the index page.\')

Following that, we’ll add one more function that will display the individual post we’re going to create later in the tutorial.

接下来,我们将添加另一个功能,该功能将显示我们稍后将在本教程中创建的单个帖子。

~/my_blog_app/blog/blogsite/views.py 〜/ my_blog_app / blog / blogsite / views.py

...def individual_post(request):return HttpResponse(\'Hi, this is where an individual post will be.\')

Our final

views.py

file will now be as follows.

现在,我们的最终

views.py

文件如下。

~/my_blog_app/blog/blogsite/views.py 〜/ my_blog_app / blog / blogsite / views.py

from django.http import HttpResponsefrom django.shortcuts import renderdef index(request):return HttpResponse(\'Hello, welcome to the index page.\')def individual_post(request):return HttpResponse(\'Hi, this is where an individual post will be.\')

When you are finished editing the file, be sure to save and exit. In nano, you can press

CTRL

and

X

, then

Y

, then

ENTER

.

完成文件编辑后,请确保保存并退出。 在nano中,您可以按

CTRL

X

,然后按

Y

,然后按

ENTER

Right now, there is no designated URL that these functions are pointing to, so we’ll have to add that to our

urlpatterns

block within our URL configuration file. With the views added, let’s move on to mapping URLs to them via this configuration file so that we can view the pages we’ve created.

目前,这些函数都没有指向指定的URL,因此我们必须将其添加到URL配置文件中的

urlpatterns

块中。 添加了视图之后,让我们继续通过此配置文件将URL映射到它们,以便我们可以查看已创建的页面。

第2步-将URL映射到视图 (Step 2 — Map URLs to Views)

With Django, we can design our own URLs to use with our app. This is done in pure Python by using a file commonly referred to as your URLconf or “URL configuration” file.

使用Django,我们可以设计自己的URL以与我们的应用程序一起使用。 在纯Python中,这是通过使用通常称为URLconf或“ URL配置”文件的文件来完成的。

In order for the web page to be displayed, Django first has to determine the root

URLconf

module to use, then proceeds to look for

urlpatterns

, a list data structure containing all of the URL patterns. Django then goes through each URL pattern until it finds the first one that matches. Once a match is found, Django finds the associated view, and that view function will receive data pertaining to the URL pattern and an

HttpRequest

object. If there is a failure at any point throughout this process, an error-handling view is shown instead.

为了显示该网页,Django首先必须确定要使用的根

URLconf

模块,然后继续查找

urlpatterns

,这是一个包含所有URL模式的列表数据结构 。 然后Django遍历每个URL模式,直到找到第一个匹配的URL模式。 找到匹配项后,Django将找到关联的视图,该视图函数将接收与URL模式和

HttpRequest

对象有关的数据。 如果在此过程中的任何时候都出现故障,则会显示一个错误处理视图 。

In this section, we’ll be working with two different

urls.py

files in two different directories of our app.

在本节中,我们将在应用程序的两个不同目录中使用两个不同的

urls.py

文件。

While in the

~/my_blog_app/blog/blogsite

directory, open the

urls.py

file — also known as your URLconf file — for editing. We’ll use nano here to edit the file.

~/my_blog_app/blog/blogsite

目录中,打开

urls.py

文件(也称为URLconf文件)进行编辑。 我们将在此处使用nano来编辑文件。

  • nano urls.py

    纳米urls.py

Change the file so that it is the same as the file below, with the

urlpatterns

list.

更改文件,使其与下面的文件相同,并带有

urlpatterns

列表。

~/my_blog_app/blog/blogsite/urls.py 〜/ my_blog_app / blog / blogsite / urls.py

from django.urls import pathfrom . import viewsurlpatterns = [path(\'\', views.index, name=\'index\'),path(\'post/\', views.individual_post, name=\'individual_post\')]

When you are finished adding the above lines, save and close the file.

完成添加以上各行后,保存并关闭文件。

Once we’ve updated the

blogsite

directory’s URLconf file, we’ll include it in the

blog

directory’s URLconf or else it won’t be recognized. We need to do this because it is set as the

ROOT_URLCONF

in our settings file. This means that Django is looking at the

blog

directory’s URLconf for

urlpatterns

.

更新

blogsite

目录的URLconf文件后,我们会将其包含在

blog

目录的URLconf中,否则它将无法识别。 我们需要这样做,因为在我们的设置文件

ROOT_URLCONF

其设置为

ROOT_URLCONF

。 这意味着Django正在查看

blog

目录的URLconf中的

urlpatterns

To include our

blogsite

URLconf within our

blog

URLconf, we’ll need to navigate to that directory.

要将我们的

blogsite

URLconf包含在我们的

blog

URLconf中,我们需要导航到该目录。

  • cd ~/my_blog_app/blog/blog

    cd〜/ my_blog_app / blog / blog

Once you are there, you can open the URLconf file with nano or another text editor of your choice.

到达那里后,您可以使用nano或您选择的其他文本编辑器打开URLconf文件。

  • nano urls.py

    纳米urls.py

Within this file, we’ll add the following lines to include the

/blogsite/urls.py

file we have just worked with, which is indicated in the second line.

在此文件中,我们将添加以下行以包含我们刚刚使用过的

/blogsite/urls.py

文件,该文件在第二行中指出。

~/my_blog_app/blog/blog/urls.py 〜/ my_blog_app / blog / blog / urls.py

from django.contrib import adminfrom django.urls import include, pathurlpatterns = [path(\'admin/\', admin.site.urls),path(\'\', include(\'blogsite.urls\'))]

Save and close the file.

保存并关闭文件。

Now let’s open a web browser in order to navigate to the URLs we’ve created and verify that they display the text we’ve added to the views. We’ll need to move into the parent directory to access the

manage.py

file that serves the Django app.

现在,我们打开一个网络浏览器,以导航到我们创建的URL,并验证它们是否显示了我们添加到视图中的文本。 我们需要进入父目录以访问为Django应用提供服务的

manage.py

文件。

  • cd ..

    光盘..

Issue the following command. You can replace

0.0.0.0

with your IP address below.

发出以下命令。 您可以使用下面的IP地址替换

0.0.0.0

  • python manage.py runserver 0.0.0.0:8000

    python manage.py runserver 0.0.0.0:8000

Within your web browser, navigate to your IP address, port 8000:

在您的Web浏览器中,导航到IP地址,端口8000:

your-server-ip:8000

You will receive a webpage similar to the following:

您将收到类似于以下内容的网页:

Next, navigate to the following URL:

接下来,导航到以下URL:

your-server-ip:8000/post/

From here, the following webpage should be displayed:

从此处开始,将显示以下网页:

We have now verified that the two

urls.py

files work, and the data shows us exactly what we’d expect. With this working, let’s add some real data into our blog.

现在,我们已经验证了这两个

urls.py

文件可以正常工作,并且数据向我们展示了我们所期望的。 通过这项工作,让我们将一些真实数据添加到我们的博客中。

第3步-创建博客文章 (Step 3 — Create a Blogpost)

Now that you understand the fundamentals of how URL patterns and views work, let’s add a blog post and get that to display on the webpage instead of the text we’ve hardcoded into the Python files.

现在,您已经了解了URL模式和视图工作原理的基础,让我们添加一个博客文章,并将其显示在网页上,而不是我们已硬编码到Python文件中的文本上。

We’ll create a post through the admin page we’ve previously set up. With your server serving the Django app, use a web browser to navigate to the admin

Blogsite

page at:

我们将通过之前设置的管理页面创建一个帖子。 在您的服务器为Django应用提供服务的情况下,使用网络浏览器导航至以下位置的管理

Blogsite

页面:

your-server-ip:8000/admin/blogsite/

In the interface, click the

+ Add

link located in the

Posts

row to start populating the database with an example blog post.

在界面中,单击“

Posts

行中的

+ Add

链接以开始使用示例博客帖子填充数据库。

Upon clicking the link, you’ll receive an input form like this:

单击链接后,您将收到如下输入表单:

Whenever you want to add a post, you’ll go to this page to do so. Alternatively, you can edit posts with the

Change

link.

每当您要添加信息时,都将转到此页面。 或者,您可以使用“

Change

链接编辑帖子。

In the form, you’ll be able to edit the following fields:

在表单中,您将能够编辑以下字段:

Field Content
Title
Add your desired blog post title here, for example

My First Blog Post

.

Slug
This refers to the part of a URL which identifies a valid web address element with human-readable keywords. This is generally derived from the title of the page, so in this case we can use

my-first-blog-post

.

Content
This is the body of your blog post. We will just be adding

Hello, World!

for example purposes, but this is where you can be verbose.

Author
In this field, add your relevant name or username. We will use

Sammy

.

领域 内容
Title
在此处添加所需的博客文章标题,例如“

My First Blog Post

Slug
这是指URL的一部分,该部分用人类可读的关键字标识有效的网址元素。 通常,这是从页面标题得出的,因此在这种情况下,我们可以使用

my-first-blog-post

Content
这是您的博客文章的正文。 我们只会添加

Hello, World!

出于示例目的,但是您可以在此处进行详细说明。

Author
在此字段中,添加您的相关名称或用户名。 我们将使用

Sammy

Fill out the blog post form as you see fit for your testing purposes.

填写您认为适合测试目的的博客文章表格。

Once you have added example data into the page, click the

SAVE

button. You’ll receive the following confirmation page:

将示例数据添加到页面后,单击“

SAVE

按钮。 您将收到以下确认页面:

Congratulations! You’ve created your first blog post!

恭喜你! 您已经创建了第一篇博客文章!

Next, let’s verify that it has added a row to the MySQL database that contains the data we just entered into the admin interface.

接下来,让我们验证它是否已在MySQL数据库中添加了一行,其中包含我们刚刚在管理界面中输入的数据。

步骤4 —显示数据库数据 (Step 4 — Display Database Data)

At this point, we need to move into MySQL, so stop the current server process via the terminal by typing

CTRL + C

, then open up your MySQL interpreter. Our user for our Django app’s database is

djangouser

, but be sure to use the right user for your project.

此时,我们需要进入MySQL,因此通过终端输入

CTRL + C

来停止当前服务器进程,然后打开MySQL解释器。 Django应用程序数据库的用户为

djangouser

,但请确保为您的项目使用正确的用户。

  • mysql -u djangouser

    mysql -u djangouser

Once you’re in the MySQL prompt, move into the

blog_data

database (or the database that is correct for your project):

进入MySQL提示符后,移至

blog_data

数据库(或对您的项目正确的数据库):

  • use blog_data;

    使用blog_data;

Then display the contents of the

blogsite_post

table.

然后显示

blogsite_post

表的内容。

  • select * from blogsite_post;

    选择* from blogsite_post;

You’ll receive output similar to the following, which should display the information you added into the admin user interface.

您将收到类似于以下内容的输出,其中应显示您添加到admin用户界面中的信息。

Output+----+--------------------+--------------------+---------------+----------------------------+--------+| id | title              | slug               | content       | created_on                 | author |+----+--------------------+--------------------+---------------+----------------------------+--------+|  1 | My First Blog Post | my-first-blog-post | Hello, World! | 2020-05-14 00:30:03.186564 | Sammy  |+----+--------------------+--------------------+---------------+----------------------------+--------+1 row in set (0.00 sec)

As shown in the output, there’s a row with the data for the post we’ve added. Let’s now reference this data into the view function for posts. Use

CTRL + D

to exit the MySQL interpreter.

如输出所示,其中一行包含我们添加的帖子的数据。 现在,将这些数据引用到帖子的视图函数中。 使用

CTRL + D

退出MySQL解释器。

Navigate to the location of the

views.py

file inside of your

blogsite

app.

导航到

blogsite

应用程序内

views.py

文件的位置。

  • cd ~/my_blog_app/blog/blogsite

    cd〜/ my_blog_app / blog / blogsite

Now open the file so that we can include our new data.

现在打开文件,以便我们可以包含新数据。

  • nano views.py

    纳米views.py

Edit the file to be the same as the file below.

编辑文件,使其与下面的文件相同。

~/my_blog_app/blog/blogsite 〜/ my_blog_app / blog / blogsite

from django.shortcuts import renderfrom django.http import HttpResponsefrom .models import Postdef index(request):return HttpResponse(\'Hello, welcome to the index page.\')def individual_post(request):recent_post = Post.objects.get(id__exact=1)return HttpResponse(recent_post.title + \': \' + recent_post.content)

In the code above, we added an additional

import

statement for

Post

. We also removed the quoted string from the

HttpResponse

and replaced it with the data from our blog post. To reference data for a particular object, we’re using the blog post ID associated with the object we’d like to show, and we’re storing that ID in a variable called

recent_post

. We can then get particular fields of that object by appending the field with a period separator.

在上面的代码中,我们为

Post

添加了附加的

import

语句。 我们还从

HttpResponse

删除了带引号的字符串,并将其替换为博客文章中的数据。 为了引用特定对象的数据,我们使用与我们要显示的对象相关联的博客文章ID,并将该ID存储在名为

recent_post

的变量中。 然后,我们可以通过在字段后面添加句点分隔符来获取该对象的特定字段。

Once you have saved and closed the file, navigate to the location of the

manage.py

file to run the Django app.

保存并关闭文件后,导航至

manage.py

文件的位置以运行Django应用。

  • cd ~/my_blog_app/blog

    cd〜/ my_blog_app / blog

  • python manage.py runserver 0.0.0.0:8000

    python manage.py runserver 0.0.0.0:8000

From a web browser, navigate to the following address:

在网络浏览器中,导航到以下地址:

your-server-ip:8000/post/

Here, we’ll see the changes we have made; the page will be similar to this, displaying the text you added to the post.

在这里,我们将看到所做的更改; 该页面将与此类似,显示您添加到帖子中的文本。

When you’re finished inspecting the page, press

CTRL + C

in the terminal to stop the process from running.

检查完页面后,请在终端中按

CTRL + C

以停止该进程的运行。

To deactivate your programming environment, you can type the

deactivate

command and then exit the server.

要停用您的编程环境,您可以键入

deactivate

命令,然后退出服务器。

结论 (Conclusion)

In this tutorial we have created views, mapped URL patterns, and displayed text on a web page from our blog post database.

在本教程中,我们已经从博客文章数据库中创建了视图,映射的URL模式并在网页上显示了文本。

The next tutorial will cover how to actually make this more aesthetically pleasing by using HTML to create Django templates. So far, this series has covered Django models and Django views. Templates are the last crucial part when it comes to the foundation of your Django application.

下一个教程将介绍如何通过使用HTML创建Django 模板,使这实际上在美学上更令人愉悦。 到目前为止,本系列文章涵盖了Django模型和Django视图。 模板是Django应用程序基础的最后一个至关重要的部分。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-create-views-for-django-web-development

django 创建视图

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » django 创建视图_如何为Django Web开发创建视图