[Django]-Change the text on Django Admin's "Add another SomeObject"-button when showing inlines

1๐Ÿ‘

โœ…

By adding verbose_name and verbose_name_plural to MeasurementInline, I managed to change the text (in this case to start with a lower case "m"):

class MeasurementInline(InlineModelAdmin):
    model = Measurement
    extra = 0
    verbose_name = 'measurement'
    verbose_name_plural = 'measurements'

1๐Ÿ‘

I didnโ€™t like the solution. So for every one who wants to change whole text
"Add another {obj_verbose_name}โ€™, here is what i came up with

class InlineAdminFormSetOnlyAddTextInAddInline(helpers.InlineAdminFormSet):
def inline_formset_data(self):
    return json.dumps({
        'name': '#%s' % self.formset.prefix,
        'options': {
            'prefix': self.formset.prefix,
            'addText': gettext('Add'),
            'deleteText': gettext('Remove'),
        }
    })

and here how i implement BaseAdmin class
you need to override get_inline_formsets โ€“ method

like this:

    def get_inline_formsets(self, request, formsets, inline_instances, obj=None):

      can_edit_parent = self.has_change_permission(request, obj) if obj else self.has_add_permission(request)
    inline_admin_formsets = []
    for inline, formset in zip(inline_instances, formsets):
        fieldsets = list(inline.get_fieldsets(request, obj))
        readonly = list(inline.get_readonly_fields(request, obj))
        if can_edit_parent:
            has_add_permission = inline.has_add_permission(request, obj)
            has_change_permission = inline.has_change_permission(request, obj)
            has_delete_permission = inline.has_delete_permission(request, obj)
        else:
            # Disable all edit-permissions, and overide formset settings.
            has_add_permission = has_change_permission = has_delete_permission = False
            formset.extra = formset.max_num = 0
        has_view_permission = inline.has_view_permission(request, obj)
        prepopulated = dict(inline.get_prepopulated_fields(request, obj))
        inline_admin_formset = InlineAdminFormSetOnlyAddTextInAddInline(
            inline, formset, fieldsets, prepopulated, readonly, model_admin=self,
            has_add_permission=has_add_permission, has_change_permission=has_change_permission,
            has_delete_permission=has_delete_permission, has_view_permission=has_view_permission,
        )
        inline_admin_formsets.append(inline_admin_formset)

or like this:

def get_inline_formsets(self, request, formsets, inline_instances, obj=None):
   formsets_ = super().get_inline_formsets(request, formsets, inline_instances, obj)
   for formset_obj in formsets_:
      formset_obj.__class__ = InlineAdminFormSetOnlyAddTextInAddInline
   return formsets_

if someone knows a better solution im glad to hear it.

๐Ÿ‘คdane4kq

Leave a comment