Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In django admin, there are fields I'd like to require if a model is being edited standalone. If it is inline, I don't want them to be required. Is there a way to do this?

like image 438
Mitch Avatar asked Jun 29 '09 20:06

Mitch


2 Answers

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
like image 161
Chris Pratt Avatar answered Oct 05 '22 21:10

Chris Pratt


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.

like image 33
Daniel Roseman Avatar answered Oct 05 '22 22:10

Daniel Roseman