我可以使用 mixins 组合基于 Create 和 List 类的通用视图吗?

发布于 2024-12-06 19:35:03 字数 568 浏览 2 评论 0原文

我正在寻找将 List 和 Create 功能与通用类视图结合起来的最简单方法。
我想要一个包含项目列表和用于在底部添加新项目的表单的页面。

我认为 mixin 架构将允许组合必要的类,但我还没有运气。

这几乎可以工作:

class ResourceListView(ListView, BaseCreateView):
    context_object_name = 'resources'
    model = Resource
    form_class = ResourceForm

但是 form 在模板内部无法访问,并且在无效输出时崩溃(当表单有效时,就很好)。
这可能与多重继承有关,但我还不太喜欢 Python,所以它太令人困惑了。

有没有一种简单的方法将一些 mixins 组合到查看并创建视图,还是我必须推出自己的视图?

I'm looking for the easiest way to combine List and Create functionally with generic class views.
I want to have a page that has an item list and a form to add a new item on the bottom.

I thought that mixin architecture would allow to combine necessary classes but I had no luck yet.

This almost works:

class ResourceListView(ListView, BaseCreateView):
    context_object_name = 'resources'
    model = Resource
    form_class = ResourceForm

But form isn't accessible inside template and the thing crashes on invalid output (when form is valid, it's fine).
This may have to do with multiple inheritance but I'm not really into Python yet so it gets too confusing.

Is there a simple way to combine some of the mixins into a view-and-create View, or do I have to roll out my own?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绿光 2024-12-13 19:35:03

注意:我不再提倡这种解决方案,因为这是一个更干净的解决方案。


通过反复试验(并查看 Django 源代码),我写了这样的内容:

class ListCreateView(ListView, BaseCreateView):
    def get_context_data(self, **kwargs):
        self.object = None
        self.object_list = self.get_queryset()

        form_class = self.get_form_class()
        form = self.get_form(form_class)

        kwargs.update({'object_list': self.object_list, 'form': form})

        context = super(ListCreateView, self).get_context_data(**kwargs)
        return context

对于创建和列表都可以正常工作(尽管它可能会发出一些额外的数据库调用,但不确定)。

Note: I no longer advocate this solution, as this is a much cleaner one.

By trial and error (and looking at Django source), I wrote this:

class ListCreateView(ListView, BaseCreateView):
    def get_context_data(self, **kwargs):
        self.object = None
        self.object_list = self.get_queryset()

        form_class = self.get_form_class()
        form = self.get_form(form_class)

        kwargs.update({'object_list': self.object_list, 'form': form})

        context = super(ListCreateView, self).get_context_data(**kwargs)
        return context

Works fine both for creating and listing (although it may issue a few extra database calls, not sure).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文