Note that there are some explanatory texts on larger screens.

plurals
  1. POValidating abstract meta class with dynamic fields
    primarykey
    data
    text
    <p>I have an abstract <code>Form</code> class that consists of dynamic fields:</p> <pre><code>class AddressForm(forms.Form): def __init__(self, all_required=True, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) self.fields['street_num'] = forms.CharField(max_length=10, label='Street number', required=all_required) self.fields['street_dir'] = DirectionFormField(required=all_required) self.fields['street_name'] = forms.CharField(max_length=35, required=all_required) self.fields['city'] = forms.CharField(max_length=35, required=all_required) self.fields['state'] = forms.ChoiceField(choices=STATE_ABBREVS, required=all_required) self.fields['zip'] = ZipCodeFormField(max_length=5, required=all_required) class Meta: abstract = True </code></pre> <p>Here's how I'm using it:</p> <pre><code>class AddressCreateForm(AddressForm): name = forms.CharField(max_length=30) </code></pre> <p>If I call is_valid() on a <code>AddressCreateForm</code> object in a view, I find that it always returns false. However, no errors are returned. If the <code>AddressForm</code> class does not have dynamic fields as below, everything works fine:</p> <pre><code>class AddressForm(forms.Form): street_num = forms.CharField(max_length=10, label='Street number') street_dir = DirectionFormField() street_name = forms.CharField(max_length=35) city = forms.CharField(max_length=35) state = forms.ChoiceField(choices=STATE_ABBREVS) zip = ZipCodeFormField(max_length=5) class Meta: abstract = True </code></pre> <p>What am I missing from the class with dynamic fields?</p> <p>As per Fiver's suggestion, <code>__init__</code> should begin with this:</p> <pre><code>class AddressForm(forms.Form): def __init__(self, *args, **kwargs): if kwargs.get('all_required') == None: all_required = True else: all_required = kwargs['all_required'] kwargs.pop('all_required') super(AddressForm, self).__init__(*args, **kwargs) #... </code></pre> <p>This works.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload