Django mutable POST没有出现在cleaning_data中

时间:2013-03-16 07:57:47

标签: django forms immutability mutable

我一直在寻找这两天,但我找不到任何可行的解决方案。

形式

class SMSSettingsForm(forms.ModelForm):
    smsQuota = forms.IntegerField(label=_("Account Quota"), max_value=432000, min_value=1, required=True, help_text=_('(mins)'), error_messages={'required': _('This field cannot be empty')})
    smsTimeout = forms.IntegerField(label=_("Timeout"), max_value=9999999, min_value=1,required=False, help_text=_("(mins)"))
    class Meta:
        model = Settings
        fields = ("smsQuota", "smsTimeout")

    def __init__(self, *args, **kwargs):
        super(SMSSettingsForm, self).__init__(*args, **kwargs)

    def save(self):
        settings = SettingsManager.get()
        settings.smsQuota = self.cleaned_data['smsQuota']
        settings.smsTimeout = self.cleaned_data['smsTimeout']

        # Following lines are extra fields, rendered by JS in HTML
        settings.ck = self.cleaned_data['ck']
        settings.ck_per = self.cleand_data['ck_per']

        settings.save()

查看

form_with_extra_elem = request.POST.copy()
form_with_extra_elem['ck'] = request.POST.get("ck")
form_with_extra_elem['ck_per'] = request.POST.get("ck_per")
# The two lines above didn't work, so I tried the following, but didn't work again
#form_with_extra_elem.update({'ck': request.POST.get("ck")})
#form_with_extra_elem.update({'ckper': request.POST.get("ck_per")})
form = SMSSettingsForm(form_with_extra_elem)

你知道如何解决这个问题吗?我认为新元素没有通过validation,所以我不能使用它们。但是如何让他们这样做呢?实际上,我不需要任何验证 - 除了cleaned_data之外还有其他方法来访问表单参数吗?

1 个答案:

答案 0 :(得分:1)

我不明白你为什么只想通过JS添加额外的字段。如果您希望它们出现在cleaned_data中,则必须将其作为表单的一部分。您只需通过指定它们就可以在ModelForm上声明额外的字段,就像使用其他字段一样:

class SMSSettingsForm(forms.ModelForm):
    smsQuota = forms.IntegerField(...)
    smsTimeout = forms.IntegerField(...)
    ck_per = forms.IntegerField()
    ck = forms.IntegerField()