pythondjangourl

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!


Solution

  • 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.