Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a field required if another field is checked in Django form

I have a model like this:

class News(models.Model):
    is_activity = models.BooleanField(default=False)
    activity_name = models.CharField(max_length=240, blank=True, null=True)

What I am trying to achieve is, if is_activity is checked in I want activity_name to be required. Thus, I am trying to override the __init__ method:

class NewsForm(forms.ModelForm):
    class Meta:
        model = News

    def __init__(self, *args, **kwargs):
        super(NewsForm, self).__init__(*args, **kwargs)
        if self.fields['is_activity'] is True:
            self.fields['activity_name'].required = True


class NewsAdmin(FrontendEditableAdminMixin, admin.ModelAdmin):
    form = NewsForm

Even if I check in the is_activity the activity_name is non-required. What's wrong?

like image 329
pynovice Avatar asked Apr 02 '14 15:04

pynovice


People also ask

How can we make field required in Django?

Making Fields Required In Django Admin In order to make the summary field required, we need to create a custom form for the Post model. I am making them on the same file you can do this on a separate forms.py file as well.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

How do you make a field not editable in Django?

disabled. The disabled boolean argument, when set to True , disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.


1 Answers

The ModelForm.clean() method gives you access to the cleaned data – this is where you can include the field-specific conditional logic:

from django.core.validators import EMPTY_VALUES

class NewsForm(forms.ModelForm):
    class Meta:
        model = News

    def clean(self):
        is_activity = self.cleaned_data.get('is_activity', False)
        if is_activity:
            # validate the activity name
            activity_name = self.cleaned_data.get('activity_name', None)
            if activity_name in EMPTY_VALUES:
                self._errors['activity_name'] = self.error_class([
                    'Activity message required here'])
        return self.cleaned_data

class NewsAdmin(FrontendEditableAdminMixin, admin.ModelAdmin):
    form = NewsForm
like image 89
Bogdan Iulian Bursuc Avatar answered Oct 22 '22 15:10

Bogdan Iulian Bursuc