django-1.8:" XXXView"对象没有属性' add_error'

时间:2015-11-13 03:48:22

标签: python django

我尝试使用" add_error"功能在django 1.8。然后我收到了错误"没有add_error"的属性。 提前感谢您的帮助。

views.py

class FinalView(ListView):
    context_object_name = 'XXX'
    template_name = 'XXX.html'
    model = Final

    def get_queryset(self):
        form = InputForm(self.request.GET)        
        if form.is_valid():
            department = form.cleaned_data['department']
            person = form.cleaned_data['person']

            if department !="" and person !="":
                if Final.objects.filter(department=department,person=person).exists():
                    queryset=Final.objects.filter(department=department,person=person)
                else:
                    self.add_error(ValidationError('No corresponding data exists')) ------here reports error----
            return queryset
        return Final.objects.all()

    def get_context_data(self,**kwargs):
        context["sales"] = self.get_queryset().aggregate(Sum('sales'))

回溯

File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\list.py" in get
  159.         self.object_list = self.get_queryset()
File "C:\Users\user\Desktop\XXX\XXXX\views.py" in get_queryset
  70.                     self.add_error(ValidationError('No corresponding data exists'))
Exception Type: AttributeError at /final/
Exception Value: 'FinalView' object has no attribute 'add_error'

1 个答案:

答案 0 :(得分:3)

add_error needs to be applied to a Form,而不是ListView。

改变这个:

self.add_error(ValidationError('No corresponding data exists'))

对此:

form.add_error(ValidationError('No corresponding data exists'))

根据关于新异常的评论,add_error有两个参数:

  

Form.add_error(field, error)

     

此方法允许在Form.clean()方法中或从表单外部向特定字段添加错误;例如从一个视图。

     

field参数是应添加错误的字段的名称。如果其值为None,则错误将被视为Form.non_field_errors()返回的非字段错误。

error参数可以是一个简单的字符串,或者最好是ValidationError的一个实例。

在您的情况下,由于这与两个字段相关,您可能需要:

form.add_error(None,ValidationError('No corresponding data exists'))