Django Admin: Making mandatory fields non-mandatory dynamically
Question
How can I make mandatory fields non-mandatory when another [associated] field has a certain value?
Let's assume I have the following models:
class foo(models.Model):
bar = models.CharField(max_length=200)
foo_date = models.DateTimeField()
When I save, and bar contains a certain value, i'd like foo_date to become non-mandatory. How do I accomplish that? Thanks.
Solution
T.Stone is right. This is how you do it with a Model Form:
class foo(models.Model):
bar = models.CharField(max_length=200)
foo_date = models.DateTimeField()
class ClientAdmin( MyModelAdmin ):
form = FooModelForm
class FooModelForm( forms.ModelForm ):
def clean(self):
cleaned_data = self.cleaned_data
if cleaned_data.get("bar") == 'some_val' and not cleaned_data.get('foo_date'):
msg = 'Field Foo Date is mandatory when bar is some_val'
self._errors[field] = ErrorList([msg])
del cleaned_data[field]
return cleaned_data
OTHER TIPS
I think it would just be a matter of setting foo_barr to blank=True, and then implementing your own Form and custom validation for the Admin model to use. See this part of the documentation -- Adding custom validation to admin
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow