zoukankan      html  css  js  c++  java
  • Django_模板中的URL参数化(四)

    去除模板中的硬编码 URL

    在案例中的 test1/templates/booktest/index.html 文件里编写的链接都硬编码的链接,比如:

    <a href="/booktest/search/{{book.id}}">查看英雄</a>

    硬编码和强耦合的链接,对于一个包含很多应用的项目来说,修改起来是十分困难的。然而,因为在 booktest/urls.py 中通过 name 参数为 URL 定义了名字,我们可以在 test1/templates/booktest/index.html 文件中使用 {% url %} 标签替换硬编码部分:

    <a href="{% url 'search' book.id %}">查看英雄</a>

    因为使用了 <int:bid>  所以在使用 {% url 视图名字 %}标签替换时需要增加  book.id 参数

    这个标签的工作方式是在 booktest/urls 模块的 URL 定义中寻具有指定名字的条目。我们可以查看一下 booktest/urls 文件中,name='search' 的 URL 是在如下语句中定义的:

    ...
    # ex: /booktest/search/1
    path('search/<int:bid>', views.hero_info, name='search') 
    ...

    如果我们想改变投票详情视图的 URL,比如想改成 booktest/searchHeroInfo/1,我们不用在模板里修改任何东西(包括其它模板),只要在 booktest/urls.py 里稍微修改一下就行:

    # ex: /booktest/search/1
    path('searchHeroInfo/<int:bid>', views.hero_info, name='search')

    为 URL 名称添加命名空间

     在一个真实的 Django 项目中,可能会有五个,十个,二十个,甚至更多应用。Django 如何分辨重名的 URL 呢?举个例子,booktest 应用有 search 视图,可能另一个应用也有同名的视图。Django 如何知道 {% url %} 标签到底对应哪一个应用的 URL 呢?

    答案是:在根 URLconf 中添加命名空间。在 booktest/urls.py 文件中稍作修改,加上 app_name 设置命名空间:

    from django.urls import path
    
    from booktest import views
    
    app_name = 'booktest'
    urlpatterns = [
        # ex: /booktest/    # 调用index视图函数
        path('', views.index, name='index'),
    
        # ex: /booktest/create  # 调用create视图函数
        path('create', views.create),
    
        # ex: /booktest/delete/1
        # re_path('delete/(d+)', views.delete),   # 在path中使用正则时需要导入re_path方法
        path('delete/<int:bid>', views.delete, name='delete'),     # bid为视图函数的的形参名
    
        # ex: /booktest/search/1
        path('searchHeroInfo/<int:bid>', views.hero_info, name='search')
    ]

    现在,编辑 test1/templates/booktest/index.html 文件,从:

    <a href="{% url 'search' book.id %}">查看英雄</a>

    修改为指向具有命名空间的详细视图:

    <a href="{% url 'booktest:search' book.id %}">查看英雄</a>

     在视图函数中重定向时使用具有命名空间的视图,编辑 test1/booktest/views.py 文件,从:

    def create(request):
        book = BookInfo(btitle="流星蝴蝶剑", bpub_date=datetime.date(1995, 12, 30), bread=2, bcomment=1)
        book.save()
        return redirect("/booktest/")

    修改为:

    def create(request):
        book = BookInfo(btitle="流星蝴蝶剑", bpub_date=datetime.date(1995, 12, 30), bread=2, bcomment=1)
        book.save()
        return redirect(reverse("booktest:index"))

    若重定向的界面需要传个book.id参数,代码如下:

    def create(request):
        ...
        return redirect(reverse('booktest:index', args=(book.id,)))
  • 相关阅读:
    python文件句柄只能用一次的误解
    字符编码后续...记事本"联通"小插曲
    字符编码
    python problem
    vue-cli3 vue-config.js配置 概况
    ssh-keygen 不是内部或外部命令
    好的文章的链接收藏
    urlArgs 请require 缓存
    js 类型判断
    阻止冒泡和取消默认事件(默认行为)
  • 原文地址:https://www.cnblogs.com/testlearn/p/13898391.html
Copyright © 2011-2022 走看看