Django Form Fields required on condition

(Abdul Baseer) #1

I have a model form. I want to make one form filed required if some value is selected

below code in which i tried adding validator but didn’t worked

class ActivityTrackerModelForm(forms.ModelForm):
    activity_name = forms.ModelChoiceField(
        queryset=activity.objects.all().order_by('activity_name'),
        label='', 
        empty_label="Select Activity", 
        widget=forms.Select(
            attrs={
            'class': 'form-control',
            }
            )
        )
    project_id = forms.CharField(
        label='', 
        required=False, 
        widget=forms.TextInput(
        attrs={
            "placeholder": "Project ID", 
            'class': 'form-control'
            }
            )
        )

    class Meta:
        model = activity_tracker
        fields = ['activity_name', 'project_id']


    def clean(self):
        activity = self.cleaned_data.get('activity_name')
        if re.search("^Project.*Activities$", str(activity)):
            self.fields['project_id'].required = True

in the above if the user is selecting the activity name as Project Activities then project id should be required

0 Likes

(Christi W) #2

I don’t think you can do that. I am a database administrator and a field either allows null values or not. You can set a default value for the project_id field if you want to have it be a required field, or just keep it as is and just update the field in your code when there is a project_id.

Hope this helps!

0 Likes