第二章中,如何理解视图与路由的关系?

2026-06-10 20:583阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计312个文字,预计阅读时间需要2分钟。

第二章中,如何理解视图与路由的关系?

创建视图模块:

1.在项目的 `mysite` 文件夹中创建一个名为 `views.py` 的文件,作为视图模块。

2.编写一个简单的视图函数:

python

第二章中,如何理解视图与路由的关系?

from django.http import HttpResponse

def test_view(request): return HttpResponse(Welcome to the test view!)

创建测试视图模块:

1.在 `views.py` 文件中继续编写另一个视图函数:

python

def test_view2(request): return HttpResponse(This is another test view!)

1、创建视图模块1)创建试图模块:在项目的mysite文件夹中创建一个views.py的文件,作为视图模块。然后编写一个简单的视图脚本fromdjango.127.0.0.1:8000/hello/即可在页面显示:hello world !

    

  2、处理服务的根目录时,我们可以通过设置空的路由指向来达到目的。代码示例如下:

    a、views.py中的代码如下:

from django.http import HttpResponsedef hello(request): return HttpResponse("hello world!")def index(request): return HttpResponse("index page!")

    b、urls.py中的代码如下

from django.contrib import adminfrom django.urls import pathfrom mysite.views import hello, indexfrom django.conf.urls import urlurlpatterns = [ path('admin/', admin.site.urls), # path('hello/', hello), # path方式 url('^hello/$', hello), # url方式 path('', index), # path方式 url('^$', index), # url方式]

 

本文共计312个文字,预计阅读时间需要2分钟。

第二章中,如何理解视图与路由的关系?

创建视图模块:

1.在项目的 `mysite` 文件夹中创建一个名为 `views.py` 的文件,作为视图模块。

2.编写一个简单的视图函数:

python

第二章中,如何理解视图与路由的关系?

from django.http import HttpResponse

def test_view(request): return HttpResponse(Welcome to the test view!)

创建测试视图模块:

1.在 `views.py` 文件中继续编写另一个视图函数:

python

def test_view2(request): return HttpResponse(This is another test view!)

1、创建视图模块1)创建试图模块:在项目的mysite文件夹中创建一个views.py的文件,作为视图模块。然后编写一个简单的视图脚本fromdjango.127.0.0.1:8000/hello/即可在页面显示:hello world !

    

  2、处理服务的根目录时,我们可以通过设置空的路由指向来达到目的。代码示例如下:

    a、views.py中的代码如下:

from django.http import HttpResponsedef hello(request): return HttpResponse("hello world!")def index(request): return HttpResponse("index page!")

    b、urls.py中的代码如下

from django.contrib import adminfrom django.urls import pathfrom mysite.views import hello, indexfrom django.conf.urls import urlurlpatterns = [ path('admin/', admin.site.urls), # path('hello/', hello), # path方式 url('^hello/$', hello), # url方式 path('', index), # path方式 url('^$', index), # url方式]