Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
85 views
in Technique[技术] by (71.8m points)

What is the function of the name parameter in django.urls.path?

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

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

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!

question from:https://stackoverflow.com/questions/51922641/what-is-the-function-of-the-name-parameter-in-django-urls-path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...