Search code examples
pythondjangodjango-admindjango-extensions

Multiple Django Admin Arguments with Extensions


Is there a way to use multiple Django extensions in the admin.site.register() inside admin.py? I'm using "simple-history" and "import-export" extensions, but I can only have one of them in the admin.site.register().

Example: I have a model named, "Cars", that is using the "simple-history" extension so I need admin.site.register(Cars, SimpleHistoryAdmin), as their documentation says it should. I want to use the import/export extension as well to the same "Cars" model, but the admin.site.register() doesn't take multiple arguments for me to add it.

models.py

class Cars(models.Model):
    Year = models.CharField(max_length=30)
    Make = models.CharField(max_length=30)
    Model = models.CharField(max_length=30)
    history = HistoricalRecords()

    class Meta:
        verbose_name_plural = "Car Table"

    def __str__(self):
        return self.Make

admin.py

class CarResource(resources.ModelResource):
    class Meta:
        model = Cars
        fields = ('id','Year', 'Make', 'Model',)

class CarAdmin(ImportExportModelAdmin):
    resource_class = CarResource
    pass

#I want to use the import/export extension (code above), along with simple-history
admin.site.register(Cars, CarAdmin)
admin.site.register(Cars, SimpleHistoryAdmin)

I've tried using a proxy and inlines, but the proxy makes a new model which I don't want and when using inlines I get an error saying that it requires a foreign key, but I'm not trying to get the model objects from a different model. Naming them the same model doesn't work because the model is already registered. Any help is much appreciated!


Solution

  • In python, class can have more than one parent. Just inherit from 2 parents at once. But both ImportExportModelAdmin and SimpleHistoryAdmin are inheriting from ModelAdmin, that's not good. There is also ImportExportMixin, we can use it instead of ImportExportModelAdmin, so there will be only one reference to ModelAdmin.

    class CarResource(resources.ModelResource):
        class Meta:
            model = Cars
            fields = ('id','Year', 'Make', 'Model',)
    
    class CarAdmin(ImportExportMixin, SimpleHistoryAdmin):
        resource_class = CarResource
        pass
    
    #I want to use the import/export extension (code above), along with simple-history
    admin.site.register(Cars, CarAdmin)