Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove Add button in Django admin, for specific Model?

I have Django model "AmountOfBooks" that is used just as balance for Book model.
If this is not good pattern for database modeling just say so.

Anyway AmountOfBooks have two fields:

class AmountOfBooks(models.Model):
    book     = models.ForeignKey(Book, editable=False)
    amount   = models.PositiveIntegerField(default=0, editable=False, help_text="Amount of book.")

They are set to editable=False, because this model is meant to be edited only by code.
Eg. when book is created object for that book in AmountOfBooks is set to 0 and when books are added or taken balance is either increased or decreased.

So in this way fields for AmountOfBooks model are not shown when I click on"Add Amount of books" button in Django admin.

But I want to remove that button from Django admin just for AmountOfBooks model.
How to do it ?

UPDATE
Continuation of this question is available on How to make Django model just view (read-only) in Django Admin?

like image 228
WebOrCode Avatar asked Nov 30 '13 06:11

WebOrCode


2 Answers

It is easy, just overload has_add_permission method in your Admin class like so:

class MyAdmin(admin.ModelAdmin):
    def has_add_permission(self, request):
        return False
like image 160
Avinash Garg Avatar answered Sep 21 '22 15:09

Avinash Garg


To do it you need to override has_add_permission method in your Admin class:

class AmountOfBooksAdmin(admin.ModelAdmin):
    def has_add_permission(self, request):
        return False

    # to disable editing for specific or all fields
    # you can use readonly_fields attribute
    # (to see data you need to remove editable=False from fields in model):
    readonly_fields = ('book', 'amount')

Docs here: https://docs.djangoproject.com/en/dev/ref/contrib/admin/

like image 30
ndpu Avatar answered Sep 21 '22 15:09

ndpu