gpt4 book ai didi

django - Django基于类的 View 上的success_url的反向提示循环导入

转载 作者:行者123 更新时间:2023-12-03 12:02:17 27 4
gpt4 key购买 nike

使用基于方法的 View 时,使用 reverse 进行重定向没有提示这一点,仍然可以找到根 url conf。但是,在基于类的 View 中,它提示:

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)是这样定义的:
class BlogCreateView(generic.CreateView):
form_class = Blog
template_name = 'blog/new-post.html'
success_url = reverse('blog:list-post')

如何正确使用 reverse对于 success_url在基于类的 View 中?谢谢。

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

最佳答案

使用 reverse在您的方法中有效,因为 reverse在 View 运行时调用。

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

如果您覆盖 get_success_url , 那么你仍然可以使用 reverse , 因为 get_success_url来电 reverse当 View 运行时。
class BlogCreateView(generic.CreateView):
...
def get_success_url(self):
return reverse('blog:list-post')

但是,您不能使用 reversesuccess_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')

要回答关于重新启动 runserver 的最后一个问题, ImproperlyConfigured错误不同于 TemplateDoesNotExists因为它发生在加载 Django 应用程序时。

关于django - Django基于类的 View 上的success_url的反向提示循环导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31275574/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com