Django 简明教程

Django - Creating Views

视图函数,简称“视图”,只是接受 Web 请求并返回 Web 响应的 Python 函数。此响应可以是网页的 HTML 内容,或者重定向,或者 404 错误,或者 XML 文档,或者图像等。示例:你使用视图创建网页,请注意你需要将视图与 URL 关联起来,才能将其视为网页。

A view function, or “view” for short, is simply a Python function that takes a web request and returns a web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, etc. Example: You use view to create web pages, note that you need to associate a view to a URL to see it as a web page.

在 Django 中,必须在应用程序 views.py 文件中创建视图。

In Django, views have to be created in the app views.py file.

Simple View

我们将在 myapp 中创建一个简单的视图来表示"欢迎使用我的应用程序!"

We will create a simple view in myapp to say "welcome to my app!"

请参见以下视图 −

See the following view −

from django.http import HttpResponse

def hello(request):
   text = """<h1>welcome to my app !</h1>"""
   return HttpResponse(text)

在此视图中,我们使用 HttpResponse 呈现 HTML(正如你可能已经注意到的,我们在这个视图中对 HTML 进行硬编码)。若要将此视图当做一个页面查看,我们只需要将其映射到一个 URL(这将在后面的章节中讨论)。

In this view, we use HttpResponse to render the HTML (as you have probably noticed we have the HTML hard coded in the view). To see this view as a page we just need to map it to a URL (this will be discussed in an upcoming chapter).

我们之前使用 HttpResponse 来呈现视图中的 HTML。这不是呈现页面的最佳方式。Django 支持 MVT 模式,因此若要使先例视图类似 Django - MVT,我们需要 −

We used HttpResponse to render the HTML in the view before. This is not the best way to render pages. Django supports the MVT pattern so to make the precedent view, Django - MVT like, we will need −

模板:myapp/templates/hello.html

A template: myapp/templates/hello.html

现在,我们的视图将类似于 -

And now our view will look like −

from django.shortcuts import render

def hello(request):
   return render(request, "myapp/template/hello.html", {})

视图还可以接受参数 -

Views can also accept parameters −

from django.http import HttpResponse

def hello(request, number):
   text = "<h1>welcome to my app number %s!</h1>"% number
   return HttpResponse(text)

当链接到 URL 时,页面将显示作为参数传递的数字。请注意,参数将通过 URL 传递(下一章中讨论)。

When linked to a URL, the page will display the number passed as a parameter. Note that the parameters will be passed via the URL (discussed in the next chapter).