本文介绍了在Django ModelForm中使用clean时,获取错误对象没有属性``get''的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试自定义验证我的模型表格。为此,我编写了以下代码:
I am trying to custom validate my model form. For the purpose, I wrote the following code:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
def clean(self):
batch_start_year = self.cleaned_data.get('batch_start_year',None)
我遇到类似以下错误:
'StudentForm' object has no attribute 'get'
我尝试了另一种解决方案,但是也没有用。
I tried another solution, but it didn't work either.
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
def clean(self):
cleaned_data = super(StudentForm, self).clean()
batch_start_year = cleaned_data['batch_start_year']
请帮助我解决此问题。
完整堆栈跟踪:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/shahjahan/Desktop/jmialumniusa/jmialumniusa_app/views.py", line 18, in apply
if form.is_valid():
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 161, in is_valid
return self.is_bound and not self.errors
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 153, in errors
self.full_clean()
File "/usr/local/lib/python2.7/dist-packages/django/forms/forms.py", line 364, in full_clean
self._post_clean()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 377, in _post_clean
exclude = self._get_validation_exclusions()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 337, in _get_validation_exclusions
field_value = self.cleaned_data.get(field)
AttributeError: 'StudentForm' object has no attribute 'get'
推荐答案
您应该从 clean()
方法返回已清理的数据,否则会引发错误。
You should return cleaned data from clean()
method or raise error. You are not doing that.
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'
def clean(self):
batch_start_year = self.cleaned_data.get('batch_start_year',None)
# do something
return self.cleaned_data
这篇关于在Django ModelForm中使用clean时,获取错误对象没有属性``get''的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!