django.urls.path中的name参数的功能是什么? [英] What is the function of the name parameter in django.urls.path?

查看:484
本文介绍了django.urls.path中的name参数的功能是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在urls.py文件中创建路径时,通常会这样做:

When creating a path inside a urls.py file, one often does this:

urlpatterns = [
    path('foo/',views.FooView,name='bar'),
]

我是Django的初学者,但尚未在path函数中看到name参数的函数。此参数的作用是什么,如何在Django支持的网站内有效地使用它?简而言之,此参数的作用是什么,为什么在创建路径时包含它很重要?谢谢!

I'm a beginner to Django, but I am yet to see the function of the name parameter inside the path function. What is this parameter for, and how can one use it effectively inside a Django-powered website? In short, what does this parameter do, and why is it important to include when creating a path? Thanks!

推荐答案

有时您想命名视图,以便您可以通过名称而不是url来引用它们。这样,如果您的应用程序中的url发生更改,则只需要在一个位置( urls.py 模块)中更新代码。使用名称而不是经过硬编码的url的现有代码不需要更新。

Sometimes you want to name views so that you can refer to them by the name rather than by the url. That way, if the url changes in your app, you only need to update the code in one place (the urls.py module). Existing code, which used the name rather than the url hardcoded, does not need to be updated.

例如, reverse 实用程序函数接受此名称并返回url:

For example, the reverse utility function accepts this name and returns the url:

from django.urls import reverse
reverse('bar')

如果您不使用名称,则移动路线很麻烦-您需要在所有模板和代码中查找并更新网址。

If you do not make use of the name, moving a route is cumbersome - you need to find and update the urls throughout all the templates and the code.

这篇关于django.urls.path中的name参数的功能是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆