本文介绍了Django Class Based View 上的success_url 反向抱怨循环导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用基于方法的视图时,使用 reverse 重定向并没有抱怨这一点,仍然可以找到根 url conf.但是,在基于类的视图中,它会抱怨:

When using method-based view, redirecting with reverse didn't complain about this and can still find the root url conf. But, in class-based views, it complain:

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')

如何在基于类的视图中为 success_url 正确使用 reverse?谢谢.

How to properly use reverse for success_url in class-based views? Thanks.

PS: 而且我对为什么需要在此错误后重新启动 runserver 感兴趣(不像 TemplateDoesNotExists 这样的错误,它是无需重启runserver)

PS: And I'm interested in why it's need to restart runserver after this error (not like an error like TemplateDoesNotExists which is no need to restart runserver)

推荐答案

在您的方法中使用 reverse 有效,因为在运行视图时会调用 reverse.

Using reverse in your method works because reverse is called when the view is run.

def my_view(request):
    url = reverse('blog:list-post')
    ...

如果你覆盖了get_success_url,那么你仍然可以使用reverse,因为get_success_url在view的时候调用了reverse正在运行.

If you overrride get_success_url, then you can still use reverse, because get_success_url calls reverse when the view is run.

class BlogCreateView(generic.CreateView):
    ...
    def get_success_url(self):
        return reverse('blog:list-post')

但是,您不能将 reversesuccess_url 一起使用,因为在导入模块时会调用 reverse已加载.

However, you can't use reverse with success_url, because then reverse is called when the module is imported, before the urls have been loaded.

覆盖 get_success_url 是一种选择,但最简单的解决方法是使用 reverse_lazy 而不是反向.

Overriding get_success_url is one option, but the easiest fix is to use reverse_lazy instead of reverse.

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 应用程序加载时.

To answer your final question about restarting runserver, the ImproperlyConfigured error is different from TemplateDoesNotExists because it occurs when the Django application is loaded.

这篇关于Django Class Based View 上的success_url 反向抱怨循环导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 04:12