提交表单后使用 success_url 转到根目录

use success_url to go to root directory after submit form

我有一个简单的基于 class 的视图(在应用 video 中),它使用模板 (upload_video.html) 中的表单创建对象。当我提交表单时,我只想重定向到主页或根索引。看起来这应该很容易。我收到一条错误消息,指出没有页面。我已经尝试了几种不同的方法来做到这一点,下面的代码只是一个例子。

views.py

class UploadVideo(CreateView):
  model = Video
  fields = ['title', 'description']
  template_name = 'upload_video.html'
  success_url = reverse_lazy('index.html')

upload_video.html

<form method="post">
    {% csrf_token %}
{{ form.as_p }}
    <input type="submit" value="Upload Video"/>
    </form>
</body>
</html>

root.urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', index),
    url(r'^video/', include('video.urls'))

错误

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/video/index.html
Using the URLconf defined in flash2.urls, Django tried these URL patterns, in this order:
^admin/
^$
^video/ ^upload [name='upload']
The current URL, video/index.html, didn't match any of these.

您需要将 urlname 传递给 revers_lazy 方法,而不是模板名称。尝试更改 url.py:

url(r'^$', index, name="index")

并且在 UploadVideo class:

success_url = reverse_lazy('index')