Django - ModelForm Change with ChoiceField

I have a ModelForm and i want to hide some fields and add help text according to values getting from the choiceField

ex:

if value_getting_from_the_choiceField == '1'
    hide_some fields in ModelForm
elif value_getting_from_the_choiceField == '2'
    add help text to some fields

You can use the __init__ method of your ModelForm subclass to customize the form's fields based on the value of the ChoiceField.

Here's an example:

from django import forms

class MyModelForm(forms.ModelForm):
    MY_CHOICES = (
        ('choice_1', 'Choice 1'),
        ('choice_2', 'Choice 2'),
        ('choice_3', 'Choice 3'),
            )
    choice_field = forms.ChoiceField(choices=MY_CHOICES)
other_field = forms.CharField()

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

        if self.data.get('choice_field') == 'choice_1':
            self.fields['other_field'].help_text = 'Some help text for choice 1'
        elif self.data.get('choice_field') == 'choice_2':
            self.fields['other_field'].help_text = 'Some help text for choice 2'
        elif self.data.get('choice_field') == 'choice_3':
            self.fields['other_field'].widget = forms.HiddenInput()

In this example, the other_field will have different help text depending on the value of the choice_field, and if the choice_field has a value of choice_3, the other_field will be hidden by using a HiddenInput widget.

You can also use the self.initial dictionary to set the initial value of the form fields, or the self.cleaned_data dictionary to access the cleaned data for the form after it has been submitted.

I hope this will helps! Incase of mistake, I'm beginner in django.

Back to Top