def management_form(self): """ Returns the ManagementForm instance for this FormSet. Automatically generates a default ManagementForm if it doesn't exist. """ if self.is_bound: form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): self.is_bound = False data = { self.prefix + '-' + TOTAL_FORM_COUNT: self.total_form_count(), self.prefix + '-' + INITIAL_FORM_COUNT: self.initial_form_count(), self.prefix + '-' + MIN_NUM_FORM_COUNT: self.min_num, self.prefix + '-' + MAX_NUM_FORM_COUNT: self.max_num, } self.data.update(data) self.is_bound = True form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError( _("ManagementForm data is missing or has been tampered with"), code='missing_management_form', ) else: form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MIN_NUM_FORM_COUNT: self.min_num, MAX_NUM_FORM_COUNT: self.max_num }) return form
def _management_form(self): """Returns the ManagementForm instance for this FormSet.""" data = self.data if self.initial_extra: total_form_count_keyname = '%s_%s' % (self.prefix, TOTAL_FORM_COUNT) if total_form_count_keyname in data: data[total_form_count_keyname] += len(self.initial_extra) else: data[total_form_count_keyname] = len(self.initial_extra) if self.is_bound: form = ManagementForm(data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError( 'ManagementForm data is missing or has been tampered with') else: form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MAX_NUM_FORM_COUNT: self.max_num }) return form
def management_form(self): """Returns the ManagementForm instance for this FormSet.""" initial_forms = self.initial_form_count() total_forms = initial_forms + self.extra # Allow all existing related objects/inlines to be displayed, # but don't allow extra beyond max_num. if initial_forms > self.max_num >= 0: total_forms = initial_forms elif total_forms > self.max_num >= 0: total_forms = self.max_num initial = { TOTAL_FORM_COUNT: total_forms, INITIAL_FORM_COUNT: initial_forms, MAX_NUM_FORM_COUNT: self.absolute_max, } if self.is_bound: # passing initial along w/ data just in case formset was not loaded # additionally, note that in create_edit_forms_from_data, # I manually update the data dictionary to include appropriate values for the management form form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix, initial=initial) if not form.is_valid(): raise ValidationError( ugettext('ManagementForm data is missing or has been tampered with'), code='missing_management_form', ) else: form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial=initial) return form
def _management_form(self): """Returns the ManagementForm instance for this FormSet.""" data = self.data if self.initial_extra: total_form_count_keyname = "%s_%s" % (self.prefix, TOTAL_FORM_COUNT) if total_form_count_keyname in data: data[total_form_count_keyname] += len(self.initial_extra) else: data[total_form_count_keyname] = len(self.initial_extra) if self.is_bound: form = ManagementForm(data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError("ManagementForm data is missing or has been tampered with") else: form = ManagementForm( auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MAX_NUM_FORM_COUNT: self.max_num, }, ) return form
def management_form(self): try: return super(BaseInitialGenericInlineFormSet, self).management_form except ValidationError: # Provide with better description of what is happening. form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError( u'ManagementForm data is missing or has been tampered with.' u' form: {0}, model: {1}, errors: \n{2}'.format( self.__class__.__name__, self.model.__name__, form.errors.as_text() )) else: raise
def _management_form(self): """Returns the ManagementForm instance for this FormSet.""" if self.is_bound: form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): self._non_form_errors = err else: form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MAX_NUM_FORM_COUNT: self.max_num, }) return form
def management_form(self): try: return super().management_form except ValidationError: # Provide with better description of what is happening. form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): raise ValidationError( "ManagementForm data is missing or has been tampered with." " form: {}, model: {}, errors: \n{}".format( self.__class__.__name__, self.model.__name__, form.errors.as_text(), ) ) else: raise
def management_form(self): """Returns the ManagementForm instance for this FormSet.""" if self.is_bound: form = ManagementForm(self.data, auto_id=self.auto_id, prefix=self.prefix) if not form.is_valid(): form.cleaned_data = { TOTAL_FORM_COUNT: 0, INITIAL_FORM_COUNT: 0, MIN_NUM_FORM_COUNT: 0, MAX_NUM_FORM_COUNT: 0, } else: form = ManagementForm(auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MIN_NUM_FORM_COUNT: self.min_num, MAX_NUM_FORM_COUNT: self.max_num }) return form
def bulk_view(self, request, form_url='', extra_context=None): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field) model = self.model opts = model._meta continue_requested = request.POST.get('_continue', request.GET.get('_continue')) force_continue = False inline = self.get_bulk_inline(request) formset_class = inline.get_formset(request) formset_params = {} prefix = formset_class.get_default_prefix() queryset = inline.get_queryset(request) if not self.has_add_permission(request): formset_class.max_num = 0 if request.method == 'GET': if 'pks' in request.GET and self.has_change_permission(request): pks = [ opts.pk.to_python(pk) for pk in request.GET.get('pks').split(',') ] queryset = queryset.filter(pk__in=pks) else: queryset = queryset.none() elif request.method == 'POST': management_form = ManagementForm(request.POST, prefix=prefix) if not management_form.is_valid(): raise ValidationError( _('ManagementForm data is missing or has been tampered with' ), code='missing_management_form', ) if not self.has_add_permission( request) and management_form.cleaned_data[ INITIAL_FORM_COUNT] < management_form.cleaned_data[ TOTAL_FORM_COUNT]: raise PermissionDenied if not self.has_change_permission( request ) and management_form.cleaned_data[INITIAL_FORM_COUNT] > 0: raise PermissionDenied queryset = self.transform_queryset(request, queryset, management_form, prefix) post, files, force_continue = self.transform_post_and_files( request, prefix) formset_params.update({ 'data': post, 'files': files, }) formset_params['queryset'] = queryset formset = formset_class(**formset_params) if request.method == 'POST': if formset.is_valid(): self.save_formset(request, form=None, formset=formset, change=False) if continue_requested or force_continue: # The implementation of ModelAdmin redirects to the change view if valid and continue was requested # The change view then reads the edited model again from database # In our case, we can't make a redirect as we would loose the information which models should be edited # Thus, we create a new formset with the edited models and continue as this would have been a usual GET request if self.has_change_permission(request): queryset = _ListQueryset(queryset) queryset.extend(formset.new_objects) else: queryset = _ListQueryset() formset_params.update({ 'data': None, 'files': None, 'queryset': queryset, }) formset = formset_class(**formset_params) msg = _( 'The %s were bulk added successfully. You may edit them again below.' ) % (force_text(opts.verbose_name_plural), ) self.message_user(request, msg, messages.SUCCESS) else: return self.response_bulk(request, formset) media = self.media inline_formsets = self.get_inline_formsets(request, [formset], [inline], obj=None) for inline_formset in inline_formsets: media = media + inline_formset.media errors = ErrorList() if formset.is_bound: errors.extend(formset.non_form_errors()) for formset_errors in formset.errors: errors.extend(list(iter(formset_errors.values()))) context = self.admin_site.each_context(request) context.update({ 'bulk': True, 'bulk_formset_prefix': prefix, 'bulk_upload_fields': self.get_bulk_upload_fields(request), 'title': _('Bulk add %s') % force_text(opts.verbose_name_plural), 'is_popup': (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), 'to_field': to_field, 'media': media, 'inline_admin_formsets': inline_formsets, 'errors': errors, 'preserved_filters': self.get_preserved_filters(request), 'adminform': admin.helpers.AdminForm(ManagementForm(), [], {}), }) context.update(extra_context or {}) return self.render_change_form(request, context, add=True, change=False, obj=None, form_url=form_url)
def bulk_view(self, request, form_url='', extra_context=None): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField("The field %s cannot be referenced." % to_field) model = self.model opts = model._meta # TODO add proper permission handling: if deleted row, ignore the delete; if no add permission, set max_num for formset; if no change permission, don't include them in queryset, and remove them after adding them continue_requested = request.POST.get('_continue', request.GET.get('_continue')) force_continue = False inline = self.get_bulk_inline(request) formset_class = inline.get_formset(request) formset_params = {} prefix = formset_class.get_default_prefix() queryset = inline.get_queryset(request) if not self.has_add_permission(request): formset_class.max_num = 0 if request.method == 'GET': if 'pks' in request.GET and self.has_change_permission(request): pks = [opts.pk.to_python(pk) for pk in request.GET.get('pks').split(',')] queryset = queryset.filter(pk__in=pks) else: queryset = queryset.none() elif request.method == 'POST': management_form = ManagementForm(request.POST, prefix=prefix) if not management_form.is_valid(): raise ValidationError( _('ManagementForm data is missing or has been tampered with'), code='missing_management_form', ) if not self.has_add_permission(request) and management_form.cleaned_data[INITIAL_FORM_COUNT] < management_form.cleaned_data[TOTAL_FORM_COUNT]: raise PermissionDenied if not self.has_change_permission(request) and management_form.cleaned_data[INITIAL_FORM_COUNT] > 0: raise PermissionDenied queryset = self.transform_queryset(request, queryset, management_form, prefix) post, files, force_continue = self.transform_post_and_files(request, prefix) formset_params.update({ 'data': post, 'files': files, }) formset_params['queryset'] = queryset formset = formset_class(**formset_params) if request.method == 'POST': if formset.is_valid(): # TODO log add / change self.save_formset(request, form=None, formset=formset, change=False) if continue_requested or force_continue: # The implementation of ModelAdmin redirects to the change view if valid and continue was requested # The change view then reads the edited model again from database # In our case, we can't make a redirect as we would loose the information which models should be edited # Thus, we create a new formset with the edited models and continue as this would have been a usual GET request if self.has_change_permission(request): queryset = _ListQueryset(queryset) queryset.extend(formset.new_objects) else: queryset = _ListQueryset() formset_params.update({ 'data': None, 'files': None, 'queryset': queryset, }) formset = formset_class(**formset_params) msg = _('The %s were bulk added successfully. You may edit them again below.') % (force_text(opts.verbose_name_plural),) self.message_user(request, msg, messages.SUCCESS) else: return self.response_bulk(request, formset) media = self.media inline_formsets = self.get_inline_formsets(request, [formset], [inline], obj=None) for inline_formset in inline_formsets: media = media + inline_formset.media context = dict( self.admin_site.each_context(request), bulk=True, bulk_formset_prefix=prefix, bulk_upload_fields=self.get_bulk_upload_fields(request), title=_('Bulk add %s') % force_text(opts.verbose_name_plural), is_popup=(IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), to_field=to_field, media=media, inline_admin_formsets=inline_formsets, # TODO errors (helpers.AdminErrorList(form, formsets)) errors=None, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) return self.render_change_form(request, context, add=True, change=False, obj=None, form_url=form_url)
def bulk_view(self, request, form_url='', extra_context=None): to_field = request.POST.get(TO_FIELD_VAR, request.GET.get(TO_FIELD_VAR)) if to_field and not self.to_field_allowed(request, to_field): raise DisallowedModelAdminToField( "The field %s cannot be referenced." % to_field) model = self.model opts = model._meta continue_requested = request.POST.get('_continue', request.GET.get('_continue')) force_continue = False inline = self.get_bulk_inline(request) formset_class = inline.get_formset(request) formset_params = {} prefix = formset_class.get_default_prefix() queryset = inline.get_queryset(request) if not self.has_add_permission(request): formset_class.max_num = 0 if request.method == 'GET': if 'pks' in request.GET and self.has_change_permission(request): pks = [ opts.pk.to_python(pk) for pk in request.GET.get('pks').split(',') ] queryset = queryset.filter(pk__in=pks) else: queryset = queryset.none() elif request.method == 'POST': management_form = ManagementForm(request.POST, prefix=prefix) if not management_form.is_valid(): raise ValidationError( _('ManagementForm data is missing or has been tampered with' ), code='missing_management_form', ) if not self.has_add_permission( request) and management_form.cleaned_data[ INITIAL_FORM_COUNT] < management_form.cleaned_data[ TOTAL_FORM_COUNT]: raise PermissionDenied if not self.has_change_permission( request ) and management_form.cleaned_data[INITIAL_FORM_COUNT] > 0: raise PermissionDenied queryset = self.transform_queryset(request, queryset, management_form, prefix) post, files, force_continue = self.transform_post_and_files( request, prefix) formset_params.update({ 'data': post, 'files': files, }) formset_params['queryset'] = queryset formset = formset_class(**formset_params) if request.method == 'POST': if formset.is_valid(): self.save_formset(request, form=None, formset=formset, change=False) if continue_requested or force_continue: # The implementation of ModelAdmin redirects to the change view if valid and continue was requested # The change view then reads the edited model again from database # In our case, we can't make a redirect as we would loose the information which models should be edited # Thus, we create a new formset with the edited models and continue as this would have been a usual GET request if self.has_change_permission(request): queryset = _ListQueryset(queryset) queryset.extend(formset.new_objects) else: queryset = _ListQueryset() formset_params.update({ 'data': None, 'files': None, 'queryset': queryset, }) formset = formset_class(**formset_params) msg = _( 'The %s were bulk added successfully. You may edit them again below.' ) % (force_text(opts.verbose_name_plural), ) self.message_user(request, msg, messages.SUCCESS) else: return self.response_bulk(request, formset) media = self.media inline_formsets = self.get_inline_formsets(request, [formset], [inline], obj=None) for inline_formset in inline_formsets: media = media + inline_formset.media errors = ErrorList() if formset.is_bound: errors.extend(formset.non_form_errors()) for formset_errors in formset.errors: errors.extend(list(six.itervalues(formset_errors))) print("type(inline_formsets)") print(type(inline_formsets)) print(inline_formsets) print(*inline_formsets, sep=", ") print("request") print(type(request)) print(request) context = dict( self.admin_site.each_context(request) if django.VERSION >= (1, 8) else self.admin_site.each_context(), bulk=True, bulk_formset_prefix=prefix, bulk_upload_fields=self.get_bulk_upload_fields(request), title=_('Bulk add %s') % force_text(opts.verbose_name_plural), is_popup=(IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), to_field=to_field, media=media, inline_admin_formsets=inline_formsets, errors=errors, preserved_filters=self.get_preserved_filters(request), # adminform=inline_formsets, # adminform=super(BulkModelAdmin, self).get_form(request, **kwargs) #kwargs not define # adminform=super(BulkModelAdmin, self).get_form(request) #object 'ContainerForm' has no attribute 'form' # searching for ContainerForm gives me nothing #writing a dummy form - uses models # adminform=DummyModelForm # but that ModelForm has no modelclass, nothing in models.py ) context.update(extra_context or {}) # print(context) return self.render_change_form(request, context, add=True, change=False, obj=None, form_url=form_url)