Django:重定向到视图函数和重定向到 url(来自 urls.py 文件)有什么区别

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

哪个是better/standard练习?

  return redirect('index')
  return redirect('/users/new')

索引是视图函数

/users/new 是来自 urls.py

的 urlpatterns

直接使用网址是discouraged by Django's documentation(我加粗):

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.

在其他情况下,您可能希望对模型使用 reverse() or {% url %}, or to add a get_absolute_url() 方法。

我认为您示例中的索引不是视图函数,而是 url-名称 url(r'^some/url/to/index', views.index_2, name='index')

视图函数可以有 index_2 名称和任何 url 路径,但您使用 "index" 进行重定向,例如 return redirect(reverse('index')).

如您所见,重定向只接受一个 url 路径,然后反向函数接收一个 url 名称和 return 一个 url 路径,在示例中反向将 return "some/url/to/index"