我的表单中的数据清理出了问题。当我在单独的字段清理方法中调用调试器时,清理后的版本中缺少一半数据。这是代码的简化版本:
class MealForm(forms.Form):
def __init__(self, *args, **kwargs):
# call super(), do some stuff, then declare some fields:
self.fields['meal'] = forms.CharField(required=True, max_length=255)
self.fields['sugar'] = forms.CharField(required=False, max_length=255)
self.fields['salt'] = forms.CharField(required=False, max_length=255)
def clean_meal(self):
pdb.set_trace() # insert a breakpoint to inspect self.cleaned_data.keys() and self.data.keys()
meal_value = self.cleaned_data['meal']
# dict of all the various utility functions because python doesn't have 'switch'
process_meal_type = {
'dessert': self.process_sugar,
'main course': self.process_salt,
}
try:
process_meal_type[meal_value]()
except KeyError:
raise forms.ValidationError( "Incorrect meal type: " + str(meal_value) )
return meal_value
def process_sugar(self):
if not self.cleaned_data.get('sugar'):
raise ValidationError ( "Desserts must contain sugar")
else:
do_something_with_the_sugar_data()
如果我发表评论clean_meal
并在clean
中添加了断点,我会注意到self.cleaned_data
符合预期:所有表单字段都存在并计入。我没有在其他任何字段上调用单个clean_*
方法。
发生了什么?
答案 0 :(得分:2)
因为各个字段清理方法提供了填充src
的数据 - 这就是它们的用途。因此,您无法访问尚未调用其干净方法的字段的数据。