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?
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
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.
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