[Solved]-In Django admin, can I require fields in a model but not when it is inline?

28👍

While Daniel Roseman’s answer works, it’s not the best solution. It requires a bit of code duplication by having to re-declare the form field. For example, if you had a verbose_name on that field, you would also have to add label='My verbose_name already set on model' to the CharField line, since re-declaring the whole field basically erases everything set on your model for that field.

The better approach is to override the form’s __init__ method and explicitly set field.required to True or False there.

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)

        self.fields['myfield'].required = True

12👍

Sure. Just define a custom form, with your required field overridden to set required=True, and use it in your admin class.

from django import forms

class MyForm(forms.ModelForm):
    required_field = forms.CharField(required=True)

    class Meta:
        model = MyModel

class MyAdmin(admin.ModelAdmin):
    form = MyForm


class MyInlineAdmin(admin.ModelAdmin):
    model = MyModel

So here MyAdmin is using the overridden form, but MyInlineAdmin isn’t.

Leave a comment