I have been searching around for this for two days now, but I couldn't find any realiable solution.
我已经找了两天了,但是没有找到任何可行的解决办法。
form:
形式:
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()
view:
观点:
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)
Do you have any idea how to solve this? What I think is the new element doesn't pass by the validation
, so I cannot use them. But how to make them to do so? Actually, I don't need any validation - is there any other way than cleaned_data
, to access form parameters?
你知道怎么解决这个问题吗?我认为新元素不会通过验证,所以我不能使用它们。但如何让他们这么做呢?实际上,我不需要任何验证——除了cleaned_data之外,还有其他方法来访问表单参数吗?
1 个解决方案
#1
1
I don't understand why you want to add extra fields via JS only. If you want them to appear in cleaned_data
, they have to be part of the form. You can declare extra fields on a ModelForm simply by specifying them like you have with the other fields:
我不明白为什么你只想通过JS添加额外的字段。如果希望它们出现在cleaned_data中,它们必须是表单的一部分。您可以在ModelForm上声明额外的字段,只需像在其他字段上指定它们:
class SMSSettingsForm(forms.ModelForm):
smsQuota = forms.IntegerField(...)
smsTimeout = forms.IntegerField(...)
ck_per = forms.IntegerField()
ck = forms.IntegerField()
#1
1
I don't understand why you want to add extra fields via JS only. If you want them to appear in cleaned_data
, they have to be part of the form. You can declare extra fields on a ModelForm simply by specifying them like you have with the other fields:
我不明白为什么你只想通过JS添加额外的字段。如果希望它们出现在cleaned_data中,它们必须是表单的一部分。您可以在ModelForm上声明额外的字段,只需像在其他字段上指定它们:
class SMSSettingsForm(forms.ModelForm):
smsQuota = forms.IntegerField(...)
smsTimeout = forms.IntegerField(...)
ck_per = forms.IntegerField()
ck = forms.IntegerField()