Ticket #6075: newforms-admin_max_num.diff

File newforms-admin_max_num.diff, 2.2 KB (added by Yves Serrano, 17 years ago)
  • django/contrib/admin/options.py

     
    66from django.contrib.admin.util import get_deleted_objects
    77from django.core.exceptions import ImproperlyConfigured, PermissionDenied
    88from django.db import models
     9from django.db.models.query import Q
    910from django.http import Http404, HttpResponse, HttpResponseRedirect
    1011from django.shortcuts import get_object_or_404, render_to_response
    1112from django.utils.html import escape
     
    720721    model = None
    721722    fk_name = None
    722723    extra = 3
     724    max_num = None
    723725    template = None
    724726    verbose_name = None
    725727    verbose_name_plural = None
     
    734736        if self.verbose_name_plural is None:
    735737            self.verbose_name_plural = self.model._meta.verbose_name_plural
    736738
     739    def get_extra_max(self, obj):
     740        """Returns how many extra fields should be added.
     741        with the constrain to never add more than max_num."""
     742        # get the foreign key to lookup the name
     743        fk_parent=forms.models.get_foreign_key(self.parent_model, self.model, self.fk_name)
     744        entries_num = len(self.model.objects.filter( apply(Q, (), { fk_parent.name: obj } ) ) )
     745        if self.max_num:
     746            current_extra = self.max_num - entries_num
     747        else:
     748            current_extra = self.extra
     749        if current_extra > self.extra:
     750            current_extra = self.extra
     751        return current_extra
     752
    737753    def formset_add(self, request):
    738754        """Returns an InlineFormSet class for use in admin add views."""
    739755        if self.declared_fieldsets:
     
    748764            fields = flatten_fieldsets(self.declared_fieldsets)
    749765        else:
    750766            fields = None
    751         return forms.inline_formset(self.parent_model, self.model, fk_name=self.fk_name, fields=fields, formfield_callback=self.formfield_for_dbfield, extra=self.extra)
     767        return forms.inline_formset(self.parent_model, self.model, fk_name=self.fk_name, fields=fields, formfield_callback=self.formfield_for_dbfield, extra=self.get_extra_max(obj))
    752768
    753769    def fieldsets_add(self, request):
    754770        if self.declared_fieldsets:
Back to Top