Django 1.11-CreateView-无效的表单针对不存在的对象属性引发错误

时间:2018-08-29 20:16:16

标签: python django

Django 1.11,使用基于通用类的视图。

提交无效表单时,调用super(CreateSupport,self).get_context_data(** kwargs)引发

  

AttributeError:“ CreateSupport”对象没有属性“ object”。

期望在表单上显示验证错误。

在表单有效时查看/创建就可以了。

这是课程:

class CreateSupport(IsAdminMixin, CreateView):
model = Support
form_class = SupportForm
template_name = 'admin/support/form.html'
success_url = reverse_lazy('admin-supports')

def get_context_data(self, **kwargs):
    context = super(CreateSupport, self).get_context_data(**kwargs)
    if hasattr(self, 'object'):
        context['images_form'] = SupportForm.ProductImageFormSet(
            instance=self.object) if "validated_images_form" not in kwargs else kwargs["validated_images_form"]

    # filter the colour and size options for current vendor
    curr_vend = Vendor.objects.get(id=self.kwargs['vendorid'])
    context['colours'] = Colour.objects.filter(vendor=curr_vend)
    context['sizes'] = Size.objects.filter(vendor=curr_vend)
    return context

def form_valid(self, support_form):
    if support_form.is_valid():
        redirect = super(CreateSupport, self).form_valid(support_form)
    else:
        validated_forms_context = self.get_context_data(form=support_form)
        redirect = self.render_to_response(validated_forms_context)

    return redirect

def post(self, request, *args, **kwargs):
    support_form = SupportForm(data=request.POST)
    return self.form_valid(support_form)

到目前为止,除了this old post以外,我都无法使用self.get_object()方法找到任何解决方案,因为该方法尚未创建,显然无法使用。

跟踪:

"C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pydev\_pydevd_bundle\pydevd_exec2.py", line 3, in Exec
    exec(exp, global_vars, local_vars)
  File "<input>", line 1, in <module>
  File "C:\ProgramData\Anaconda2\envs\django3.4\lib\site-packages\django\views\generic\edit.py", line 94, in get_context_data
    return super(FormMixin, self).get_context_data(**kwargs)
  File "C:\ProgramData\Anaconda2\envs\django3.4\lib\site-packages\django\views\generic\detail.py", line 101, in get_context_data
    if self.object:
AttributeError: 'CreateSupport' object has no attribute 'object'

1 个答案:

答案 0 :(得分:0)

在Will Keeling对默认post()实现的评论之后,我接触了BaseCreateView类。

这是post()的默认实现:

def post(self, request, *args, **kwargs):
    self.object = None
    return super(BaseCreateView, self).post(request, *args, **kwargs)

因此可以通过将self.object设置为None来简单地解决问题。