Skip to content

Commit

Permalink
Added add model twice chapter
Browse files Browse the repository at this point in the history
  • Loading branch information
shabda committed Feb 19, 2018
1 parent 56ca88d commit 555c278
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
36 changes: 35 additions & 1 deletion docs/add_model_twice.rst
Original file line number Diff line number Diff line change
@@ -1,2 +1,36 @@
How to add a model twice to Django admin?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++


You need to add the :code:`Hero` model twice to the admin, one as a regular admin area, and one as read only admin. (SOme user will potentially see only the read only admin.)

If you have try to register the same model twice::

admin.site.register(Hero)
admin.site.register(Hero)

you will get an error like this::

raise AlreadyRegistered('The model %s is already registered' % model.__name__)

THe solution is to sublass the :code:`Hero` model as a ProxyModel.::

# In models.py
class HeroProxy(Hero):

class Meta:
proxy = True

...
# In admin.py
@admin.register(Hero)
class HeroAdmin(admin.ModelAdmin, ExportCsvMixin):
list_display = ("name", "is_immortal", "category", "origin", "is_very_benevolent")
....


@admin.register(HeroProxy)
class HeroProxyAdmin(admin.ModelAdmin):
readonly_fields = ("name", "is_immortal", "category", "origin",
...)

9 changes: 8 additions & 1 deletion heroes_and_monsters/entities/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from django.contrib import admin
from django.db.models import Count

from .models import Hero, Villain, Category, Origin
from .models import Hero, Villain, Category, Origin, HeroProxy

import csv
import sys
Expand Down Expand Up @@ -85,6 +85,13 @@ def is_very_benevolent(self, obj):
is_very_benevolent.boolean = True


@admin.register(HeroProxy)
class HeroProxyAdmin(admin.ModelAdmin):
list_display = ("name", "is_immortal", "category", "origin",)
readonly_fields = ("name", "is_immortal", "category", "origin",)



@admin.register(Villain)
class VillainAdmin(admin.ModelAdmin, ExportCsvMixin):
list_display = ("name", "category", "origin")
Expand Down
5 changes: 5 additions & 0 deletions heroes_and_monsters/entities/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ class Meta:
)


class HeroProxy(Hero):

class Meta:
proxy = True

class Villain(Entity):
is_immortal = models.BooleanField(default=False)

Expand Down

0 comments on commit 555c278

Please sign in to comment.