As someone else suggested in another answer, an abstract class is an obvious approach. However, the code given in that answer throws errors.
To be frank, doing this with an abstract class (as of summer 2023) is clunky and needs work arounds. Testing this is also hard, because I don't think Django removes any permissions from the auth_permission table when undoing migrations (migrate my_app 0022
where 0022 was the prefix of a previous migration)
What does NOT work:
# BROKEN, DOES NOT WORK
class MyAppBaseModel(models.Model):
class Meta:
abstract = True
permissions = (("see_details_%(class)s", "Can see details of %(class)s"),)
class ChildModel(MyAppBaseModel):
class Meta:
# Ideally would result in model getting default permissions plus "see_details_childmodel" and "foobar_childmodel"
permissions = (("foobar_childmodel", "Can foobar childmodel"),)
What DOES work (source):
- fairly short
- takes advantage of how Django does meta-class inheritance (needs explanation with comments)
- Adds to the default permissions (from what I could see)
- ALL OBJECTS GET THE SAME PERMISSION NAME
Code:
class AbstractBaseModel(models.Model):
class Meta:
abstract = True
permissions = (("see_details_generic","See details (Generic)"),) # <-- Trailing comma
class SomeClass(AbstractBaseModel):
name = models.CharField(max_length=255,verbose_name="Name")
class Meta(AbstractBaseModel.Meta): # <--- Meta Inheritance
# Results in child getting default permissions plus "see_details_generic" (NOT view_childmodel)
pass
# Still trying to figure out how to get this to work
# As written, if use the below instead of pass, it removes see_details_generic
# permissions = (("foobar_childmodel", "Can foobar childmodel"),)
P.S. An improvement to Django to help make the broken example work has been kicked around for 14 years. Hoping someone could finish it up on Github.