administrator of django custom actions

0

I'm trying to do an action for the Django-admin (trying because I'm new to this), but I can not get it to appear in the dropdown that says "Delete Selected Data / s"

My goal is to import the data of a file previously uploaded with FileField to the database to later show it to the users

admin.site.register(Data)


def some_action(self, request, queryset):
    # En principio asi obtengo la data que necesito
    # como hago para que "data ejemplo" sea el objeto que selecciono el admin?
    pe.get_records(file_name="Data Ejemplo.xls")
    # Y creo que asi obtengo la descripcion que sale en el desplegable
    self.short_description = "obtener data"


class UserAdmin(admin.ModelAdmin):
    actions = ['data import']




admin.site.unregister(User)
admin.site.register(User, UserAdmin)
    
asked by Anthony 18.08.2017 в 14:35
source

1 answer

0

According to Django's documentation at link to make an action (action) in the admin, you must follow the following steps:

  • Create the function that will be the action:

    def action_function(modeladmin, request, queryset):
        pe.get_records(file_name="Data Ejemplo.xls")
    # Se añade un atributo al objeto de la función
    action_function.short_description = 'Obtener data'
    
  • Unlike your function, you are using the argument self and also, within the function you are adding an attribute to self ( self.short_description... ). Which means that you're adding that attribute to modeladmin and not to the object of the function as such.

  • Add the function to ModelAdmin :

    class UserAdmin(admin.ModelAdmin):
        actions = [action_function]
    
  • Here the main difference is that if you see, it is a list that contains the name of the function that you created and want to use as an action, while in your code, you have a string.

    This would be enough to make Django's action and administrator issue work.

    But your code could run if you were to return a method of the class you are creating, leaving it like this:

    class UserAdmin(admin.ModelAdmin):
        actions = ['action_function']
    
        def action_function(self, request, queryset):
            pe.get_records(file_name="Data Ejemplo.xls")
        action_function.short_description = 'Obtener data'
    

    That would also work properly, any question questions. I hope I have helped you

        
    answered by 18.08.2017 в 15:57