python - Django 中 reverse() 和 reverse_lazy() 的区别

标签 python django django-views url-routing

我知道我们可以在 FBV 中使用 reverse(),在 CBV 中使用 reverse_lazy()。我知道我们必须在 CBV 中使用 reverse_lazy(),因为导入文件时不会加载 url(引用:Reverse_lazy and URL Loading?)

我不明白的是:

当我们从 FBV 调用 reverse 时,url 是如何加载的?当我们在 Django 应用程序的 urls.py 顶部导入 View 时,urlpatterns 列表尚未评估。 reverse() 如何用于 FBV 而不是 CBV?

最佳答案

考虑这两种定义 success_url 的方法。第一个被注释掉, 第二个是函数:

class NewJobCBV(LoginRequiredMixin, CreateView):
    template_name = 'company/job.html'
    form_class = newJobForm
    # success_url = reverse_lazy('newJob')

    def get_success_url(self, **kwargs):
        return reverse("newJob")

@CoffeeBasedLifeform:你是对的,类属性是在导入时评估的,我在阅读你的回答后进行了检查。所以,

  1. 如果我们使用success_url,我们必须使用reverse_lazy()
  2. 如果我们在函数内部反转,我们可以使用 reverse()

现在很清楚了。

感谢 CoffeeBasedLifeform :)

关于python - Django 中 reverse() 和 reverse_lazy() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48669514/

相关文章:

python - 在 Python 中读取 SUB 以外的行

python - 取消已挂起的 ProcessPoolExecutor future

带有formset的django保存模型

python - 如何在 Django 中预加载 Python 库?

python - 在 Python 中显示大量格式化文本

python - 快速将带有索引的 numpy 数组转换为以该索引为键的 numpy 数组的字典

python - 如何在 Django 中使用单个表单创建用户和配置文件?

django - 永远不会调用 Django 管理界面中字段的只读方法

django-django-taggit表单

django - 显示和保存 Django ArrayField