Reputation: 1973
How do you limit the inline formset in django admin?
Problem:
I have a table A with 1 to n relationship with B. Table A should have at least one Table B item and a max of 5 Table B items.
Upvotes: 28
Views: 27786
Reputation: 6486
You can do this using a Django admin inline formset
.
from django.forms.models import BaseInlineFormSet
MAX_RECORDS = 10
class ExampleFormSet(BaseInlineFormSet):
def get_queryset(self) :
qs = super(ExampleFormSet, self).get_queryset()
return qs.order_by('-date_started')[:MAX_RECORDS]
class ExampleAdmin(models.TabularInline):
model = models.Example
formset = ExampleFormSet
This way, you can filter, order, and limit your results however you want.
Upvotes: 2
Reputation: 408
The enabling / disabling of the add button in an inline is managed through the _has_add_permission
method
you could add to your inline class:
def _has_add_permission(self, request, obj=None):
# add/remove possibility to add a line to an inline
if obj.table_b_items.count() < 5:
return True
else:
return False
Upvotes: 0
Reputation: 118458
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-options
Specify max_num
in your Inline
definition to limit the number.
extra
specifies how many blank inlines to show.
Is the 1 inline required? As in you want to trigger a validation error if table B isn't filled with at least 1 row?
Upvotes: 49