当使用基于方法的视图时,重定向为reverse
没有抱怨这一点,并且仍然可以找到 root url conf。但是,在基于阶级的观点中,它抱怨:
ImproperlyConfigured at /blog/new-post/
The included urlconf 'blog.urls' does not appear to have any
patterns in it. If you see valid patterns in the file then the
issue is probably caused by a circular import.
我的类定义如下:
class BlogCreateView(generic.CreateView):
form_class = Blog
template_name = 'blog/new-post.html'
success_url = reverse('blog:list-post')
如何正确使用reverse
for success_url
在基于阶级的观点中?谢谢。
PS:我感兴趣的是为什么需要重新启动runserver
在此错误之后(不像这样的错误TemplateDoesNotExists
无需重新启动runserver
)
Using reverse
在你的方法中有效是因为reverse
当视图运行时调用。
def my_view(request):
url = reverse('blog:list-post')
...
如果你覆盖get_success_url
,那么你仍然可以使用reverse
, 因为get_success_url
calls reverse
当视图运行时。
class BlogCreateView(generic.CreateView):
...
def get_success_url(self):
return reverse('blog:list-post')
但是,您不能使用reverse
with success_url
,因为那时reverse
在导入模块时、在加载 url 之前调用。
覆盖get_success_url
是一种选择,但最简单的解决方法是使用reverse_lazy https://docs.djangoproject.com/en/1.8/ref/urlresolvers/#reverse-lazy而不是反向。
from django.urls import reverse_lazy
# from django.core.urlresolvers import reverse_lazy # old import for Django < 1.10
class BlogCreateView(generic.CreateView):
...
success_url = reverse_lazy('blog:list-post')
要回答有关重新启动 runserver 的最后一个问题,ImproperlyConfigured
错误不同于TemplateDoesNotExists
因为它是在加载 Django 应用程序时发生的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)