我尝试在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'发布于 2015-11-13 03:54:47
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'))https://stackoverflow.com/questions/33685604
复制相似问题