Skip to main content
 首页 » 编程设计

python之django-1.8 : "XXXView"object has no attribute 'add_error'

2024年08月23日40bonelee

我尝试在 Django 1.8 中使用“add_error”函数。然后我得到错误“没有 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' 

请您参考如下方法:

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)

This method allows adding errors to specific fields from within the Form.clean() method, or from outside the form altogether; for instance from a view.

The field argument is the name of the field to which the errors should be added. If its value is None the error will be treated as a non-field error as returned by Form.non_field_errors().

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

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

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