• 4.对urls.py的解释


    解释:

      路由配置文件(URL分发器),它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表。就是以这种方式告诉Django对于每个URL的处理类。Django启动的时候回去加载urls.py文件,加载那个文件可以在hello_djangohello_djangosetting.py中通过ROOT_URLCONF配置,如ROOT_URLCONF = 'hello_django.urls'(默认配置)

    理解:

      相当于spring mvc里的@RequestMapping的作用

    基本语法:

      urlpatterns = [
        url(正则表达式, view函数, 参数, 别名, 前缀),
      ]

    用法一(不带参数):

      from django.contrib import admin
      urlpatterns = [
        # url(r'^hello/', views.hello),
      ]

    用法二(不带参数):
      urlpatterns = [
        url(r'^hello/', 'hello.views.hello'),
      ]

    备注:用法一和用法二是一样的,但是方法二在1.9版本后将不再推荐使用,被标记为过时

    用法三(带参数):
      urlpatterns = [
        url(r'^hello/', 'hello.views.hello', {'name':'xiaol'}),
      ]

      相应的,view里去接收这个参数,修改为:

       

      

    关于  正则表达式:

      1.定义url访问路径:

        urlpatterns = [

          url(r'^hello/d{2}', views.hello),
        ]

      访问的时候必须在hello后面带个两位数:http://localhost:8000/hello/22

      2.传递url参数:

        urlpatterns = [

          url(r'^hello/(?P<id>d{2})', views.hello),
        ]

      意思是:在hello后面带个两位数字,并且,这个两位数字被作为参数传进去,参数名是id

      相应的,view里去接收这个参数,修改为:

      

      

    以下英文为urls.py文件自带的注释,里面的三个例子值得看

    The `urlpatterns` list routes URLs to views. For more information please see:https://docs.djangoproject.com/en/1.9/topics/http/urls/
    Examples:
      Function views
        1. Add an import: from my_app import views
        2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
      Class-based views
        1. Add an import: from other_app.views import Home
        2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
      Including another URLconf
        1. Import the include() function: from django.conf.urls import url, include
        2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))

  • 相关阅读:
    leetcode211
    leetcode209
    leetcode201
    leetcode1396
    leetcode1395
    leetcode1394
    leetcode1386
    leetcode1387
    leetcode1382
    leetcode1376
  • 原文地址:https://www.cnblogs.com/413xiaol/p/6501013.html
Copyright © 2020-2023  润新知