gpt4 book ai didi

Django - 混合 ListView 和 CreateView

转载 作者:行者123 更新时间:2023-12-03 22:48:04 26 4
gpt4 key购买 nike

我想用表单创建一个页面,每次提交表单时,它都会向表单下方的列表中添加一个项目。

我可以使用 2 页使其工作:

  • 使用 mixin 的一页 CreateView添加项目
  • 一页ListView有名单。


  • 但我试图将表单和列表放在同一页面上。所以我尝试用两个 mixin 创建一个类:
    class FormAndListView(ListView, CreateView):
    pass

    然后我使用了这个类:
    FormAndListView.as_view(
    queryset=PdfFile.objects.order_by('id'),
    context_object_name='all_PDF',
    success_url = 'listview',
    form_class = UploadFileForm,
    template_name='textfrompdf/index.html',)),

    但是当我尝试加载页面时,出现错误: Exception Value: 'FormAndListView' object has no attribute 'object'
    Traceback:
    File "C:\Program Files\Python_2.7\lib\site-packages\django\core\handlers\base.py" in get_response
    111. response = callback(request, *callback_args, **callback_kwargs)
    File "C:\Program Files\Python_2.7\lib\site-packages\django\views\generic\base.py" in view
    47. return self.dispatch(request, *args, **kwargs)
    File "C:\Program Files\Python_2.7\lib\site-packages\django\views\generic\base.py" in dispatch
    68. return handler(request, *args, **kwargs)
    File "C:\Program Files\Python_2.7\lib\site-packages\django\views\generic\list.py" in get
    122. return self.render_to_response(context)
    File "C:\Program Files\Python_2.7\lib\site-packages\django\views\generic\base.py" in render_to_response
    94. template = self.get_template_names(),
    File "C:\Program Files\Python_2.7\lib\site-packages\django\views\generic\list.py" in get_template_names
    134. names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    File "C:\Program Files\Python_2.7\lib\site-packages\django\views\generic\detail.py" in get_template_names
    122. if self.object and self.template_name_field:

    Exception Type: AttributeError at /PDF/
    Exception Value: 'FormAndListView' object has no attribute 'object'

    我不知道如何调试。从哪儿开始?

    最佳答案

    我使用了很多涉及表单和对象列表的 View 。而不是试图混合事物,我只是将查询集添加到上下文数据中,如下所示。

    class UploadFileView(CreateView):
    form_class = UploadFileForm
    success_url = 'listview'
    template_name = 'textfrompdf/index.html'

    def get_context_data(self, **kwargs):
    kwargs['object_list'] = PdfFile.objects.order_by('id')
    return super(UploadFileView, self).get_context_data(**kwargs)

    关于Django - 混合 ListView 和 CreateView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9338181/

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