Is there a way to extend another apps ModelAdmin?
I have a project that uses functionality offered by django.contrib.comments.
The CommentsAdmin ModelAdmin class has:
actions = ["flag_comments", "approve_comments", "remove_comments"]
I would like to extend the CommentsAdmin ModelAdmin in my project to include an action ban_user
.
I've tried creating my own NewCommentsAdmin(CommentsAdmin)
object in my admin.py file and registering it, but I get a notice 'AlreadyRegistered at /admin/' 'The model Comment is already registered'
.
class NewCommentAdmin(CommentAdmin):
actions = ['ban_user']
def ban_user(self, request, queryset):
pass
admin.site.register(Comment, NewCommentAdmin)
Is there a way to do this without modifying the original django.contrib.comments code?
Have a look at https://github.com/kux/django-admin-extend
It offers some easy to use functions and decorators that implement the functionality you're requesting in a very flexible manner. The documentation does a pretty good job at explaining why using this approach is better than direct inheritance.
It also has support for injecting bidirectional many to many fields.
I guess you have something like this at the top of your file:
This import executes the registration of the model (at the very bottom of this admin file) again.
One idea that doesn't look very nice (I actually haven't tried it) could be:
I guess this could be done better but it should work. To make this approach work, the application that contains this file has to be after the comments application in
INSTALLED_APPS
.Now to your class. I think if you write
actions = ['ban_user']
you actually overwrite all the actions in the parent class. I think it is the easiest way to override theget_actions
method:Hope that helps (or at least gives an idea) :)
Here's how I do it in one project for the User model. In the admin.py for my app:
Unregister the
Comment
model first.