[Answer]-Validate a dynamic select field in Django

1๐Ÿ‘

โœ…

I was able to solve this with a little overriding of a method in ChoiceField.

I added the field to the form and handled the pre-population with the self.initial:

class SchoolProductForm(forms.ModelForm):
    cip_category = common_forms.DynamicChoiceField(
        required=True, choices=(('', '----------'),))

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

        self.fields['short_description'].widget = TA_WIDGET
        self.fields['salary_info'].widget = TA_WIDGET
        self.fields['job_opportunities'].widget = TA_WIDGET
        self.fields['related_careers'].widget = TA_WIDGET
        self.fields['meta_keywords'].widget = TI_WIDGET
        self.fields['meta_description'].widget = TI_WIDGET
        self.fields['cip'].queryset = models.CIP.objects.filter(
            parent_id__isnull=True)

        # Get the top parent and pre-populate
        if 'cip' in self.initial:
            self.initial['cip'] = models.CIP.objects.get(
                pk=self.initial['cip']).top_parent()

    class Meta:
        model = models.SchoolProduct
        exclude = ('campus',)

Where DynamicChoiceField is:

class DynamicChoiceField(forms.ChoiceField):
    def valid_value(self, value):
        return True

Then, in the view I added handling in the form_valid override:

def form_valid(self, form):
    self.object = form.save(commit=False)

    # Handle the CIP code
    self.object.cip_id = self.request.POST.get('cip_subcategory')
    if self.object.cip_id == '':
        self.object.cip_id = self.request.POST.get('cip_category')

    self.object.save()
๐Ÿ‘คRico

Leave a comment