【发布时间】:2015-09-17 00:20:05
【问题描述】:
我有一个带有选择列表的表单。
当用户从award_grant_type选择列表中选择值8888或9999时,我想要一些表单输入字段中可能存在也可能不存在的数据(用户可能已经在表单文本输入中输入了数据字段,然后选择 8888 或 9999)在表单数据提交到数据库之前删除。
所以我有以下model.py代码:
.....
DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITH_PROMPT = 8888
DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITHOUT_PROMPT = 9999
.....
AWARD_GRANT_TYPES = (
(SELECT_AWARD_AND_GRANT_TYPE, _('Select Type')),
(AWARD, _('Award')),
(GRANT, _('Grant')),
(TRAVEL_GRANT, _('Travel Grant')),
(OTHER_AWARD, _('Other Award')),
(OTHER_GRANT, _('Other Grant')),
(WRITE_MY_OWN_AWARD_AND_GRANT_TYPE_DESCRIPTION, _('Write my own Type description')), #7777
(DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITH_PROMPT, _('Display only Description with prompt')), #8888
(DISPLAY_ONLY_AWARD_AND_GRANT_DESCRIPTION_WITHOUT_PROMPT, _('Display only Description without prompt')) #9999
)
user = models.ForeignKey(User)
language_version = models.ForeignKey('LanguageVersion')
award_grant_type = models.PositiveIntegerField(choices=AWARD_GRANT_TYPES, default=SELECT_AWARD_AND_GRANT_TYPE, validators=[MinValueValidator(1)])
award_grant_type_description = models.CharField(null=True, blank=True, max_length=250)
award_grant_date = models.DateField(null=True, blank=True)
award_grant_description = models.TextField(null=False, blank=False, max_length=5000)
这是我的 forms.py 干净代码,当用户在提交到数据库之前从选择列表 award_grant_type 中选择了 8888 或 9999 时,应该删除 award_grant_type_description 和 award_grant_date 字段:
def clean(self):
cd_agdf = super(AwardGrantDetailsForm, self).clean()
if 'award_grant_type' in cd_agdf:
if cd_agdf['award_grant_type'] == '':
self._errors['award_grant_type'] = self.error_class([_("You must select a Type.")])
elif cd_agdf['award_grant_type'] == 8888 or cd_agdf['award_grant_type'] == 9999:
# remove the entered values when the award grant type only requires minimum data.
self.cleaned_data.pop('award_grant_type_description', None)
self.cleaned_data.pop('award_grant_date', None)
else:
....
return cd_agdf
谁能指出我做错了什么?在表单数据提交到数据库之前,award_grant_type_description 和 award_grant_date 不会被删除。
编辑/更新
只有在更新现有记录时才会出现此问题。 在将表单保存到数据库之前,新记录会根据需要删除数据。当现有记录有一个日期字段作为数据库记录的一部分并且award_grant_type 从 1 更改为 8888 或 9999 时,award_grant_date 不会从数据库中删除。我不知道为什么。
第二次编辑
我已经发布了一个相关的帖子here。
【问题讨论】:
-
代码看起来不错。你确定
clean被调用了吗?是否正确评估了相关的if语句?我能看到的唯一潜在问题是您从self.cleaned_data弹出但返回cd_agdf;这些应该都是对同一事物的引用,但可能会更改为始终使用cd_agdf,看看是否有效。 -
感谢您的回答。我已经进行了更改,但我现在意识到问题只发生在现有记录上 - 请参阅帖子中的编辑/更新。
标签: python django python-2.7 django-forms