Unsure of approach for Django custom user groups and permissions

Viewed 100

I am creating my first Django (ver 3.1) website which is simply a blog with a home page and store page. I want to create custom user groups that define specific roles (with unique permissions) for my blog.

These groups are:

  • Reader - anonymous viewers and new accounts; has read permission for all content only
  • Author - login required; has read and create permissions; edit and delete permissions for own content only
  • Moderator - login required; has all CRUD permissions for all content
  • Admin - login required, has all permissions (superuser)

All new users by default are in the Reader group. Author would either be assigned manually or eventually by an online form application to determine eligibility. Moderator and Admin would of course be manually assigned.

I am approaching this with possible future development, such as allowing user groups to be easily extended to other website pages. For example, a 5% discount for Author users applied to all store items, etc.

Which approach to creating user groups would be best for my situation? I have seen it done within the Django Admin Panel and by creating custom User Models via extending the AbstractBaseUser and UserBaseManager classes.

1 Answers

I think extending the AbstractUser model is a good approach. How about something like this?

class CustomUser(AbstractUser):
    "Define the extra fields related to User here"""

    first_name = models.CharField(_('First Name of User'), blank=True, max_length=20)
    last_name = models.CharField(_('Last Name of User'), blank=True, max_length=20)

    #  - - - Some more User fields according to your need s

    class Meta:
        permissions = (("can_read_content", "To provide read facility on all content"),
       #---------------------
                       )
Related