I have the following form code:
class DisplaySharerForm(forms.Form):
ORDER_BY_CHOICES = (
('customer_sharer_identifier', 'customer_sharer_identifier'),
('action_count', 'action_count'),
('redirect_link', 'redirect_link'),
('enabled', 'enabled'),
('click_total', 'click_total')
)
DIRECTION = (
('DESC','DESC'),
('ASC', 'ASC')
)
#These are the sorting options. By default it's set to order by the customer_sharer_identifiers, descending, beginning at page 1.
order_by = forms.ChoiceField(choices=ORDER_BY_CHOICES, required=False,initial='customer_sharer_identifier')
direction = forms.ChoiceField(choices=DIRECTION, required=False,initial='DESC')
action_type_id = forms.IntegerField(required=False)
page_number = forms.IntegerField(required=False,initial=1)
Here's what I get when I try to create a DisplaySharerForm using the initial values:
>>> f = DisplaySharerForm({})
>>> f.is_valid()
True
>>> f.cleaned_data
{'action_type_id': None, 'direction': u'', 'page_number': None, 'order_by': u'', 'customer_sharer_identifier': None}
Why isn't cleaned_data being set to the initial values I provided and what can I do to fix it?
cleaned_data returns the cleaned values of the data bound to the form. In this case you've bound and empty dictionary to the form. The initial_data is used for the initial form display and for seeing which values have changed. You could "fix" this with a custom clean function:
class DisplaySharerForm(forms.Form):
...
def clean(self):
cleaned_data = super(DisplaySharerForm, self).clean()
for key, value in cleaned_data.items():
if not value and key in self.initial:
cleaned_data[key] = self.initial[key]
return cleaned_data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With