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?
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.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With