[Answered ]-Django: what is the difference between redirect to a view function and redirect to a url (from urls.py file)

1👍

Using URLs directly is discouraged by Django’s documentation (my bold):

A common need when working on a Django project is the possibility to obtain URLs in their final forms either for embedding in generated content (views and assets URLs, URLs shown to the user, etc.) or for handling of the navigation flow on the server side (redirections, etc.)

It is strongly desirable to avoid hard-coding these URLs (a laborious, non-scalable and error-prone strategy). Equally dangerous is devising ad-hoc mechanisms to generate URLs that are parallel to the design described by the URLconf, which can result in the production of URLs that become stale over time.

In other contexts you may wish to use reverse() or {% url %}, or to add a get_absolute_url() method to your models.

👤Chris

1👍

I think that index in your example is not a view function, but a url-name
url(r'^some/url/to/index', views.index_2, name='index')

view functions can have index_2 name and any url path, but you use “index” to redirect, for example return redirect(reverse('index')).

As you can see, redirect only accept an url path, then reverse function receive a url name and return an url path, in the example reverse will return "some/url/to/index"

Leave a comment