Mas*_*gol 20 django redirect django-views
当使用基于方法的视图时,重定向reverse
并没有抱怨这个,仍然可以找到根URL配置.但是,在基于类的视图中,它抱怨:
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.
Run Code Online (Sandbox Code Playgroud)
我的课程定义如下:
class BlogCreateView(generic.CreateView):
form_class = Blog
template_name = 'blog/new-post.html'
success_url = reverse('blog:list-post')
Run Code Online (Sandbox Code Playgroud)
如何正确地使用reverse
了success_url
基于类的看法?谢谢.
PS:我感兴趣的是为什么runserver
在这个错误之后需要重新启动(不像是一个TemplateDoesNotExists
不需要重启的错误runserver
)
Ala*_*air 48
reverse
在您的方法中使用是因为reverse
在运行视图时调用.
def my_view(request):
url = reverse('blog:list-post')
...
Run Code Online (Sandbox Code Playgroud)
如果你覆盖get_success_url
,那么你仍然可以使用reverse
,因为在运行视图时get_success_url
调用reverse
.
class BlogCreateView(generic.CreateView):
...
def get_success_url(self):
return reverse('blog:list-post')
Run Code Online (Sandbox Code Playgroud)
但是,你不能使用reverse
与success_url
,因为那时reverse
已经加载的URL之前,当模块导入叫.
覆盖get_success_url
是一种选择,但最简单的解决方法是使用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')
Run Code Online (Sandbox Code Playgroud)
要回答关于重新启动runserver的最后一个问题,ImproperlyConfigured
错误与TemplateDoesNotExists
加载Django应用程序时发生的错误不同.
尝试使用reverse_lazy
而不是reverse
在您的CBV中.它是一个懒惰的评估版本reverse
.在需要该值之前,它不会执行.
from django.core.urlresolvers import reverse_lazy
class BlogCreateView(generic.CreateView):
form_class = Blog
template_name = 'blog/new-post.html'
success_url = reverse_lazy('blog:list-post')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21440 次 |
最近记录: |