Adding user roles to my Django e-commerce site

Hey everyone! I just finished my Django e-commerce project and now I want to add different user roles like admin, staff, merchant, and customer. But I’m stuck and could use some help.

I’ve got a Customer model that looks like this:

class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    contact = models.CharField(max_length=10)
    location = models.TextField(max_length=30)
    region = models.TextField(max_length=30)

    def __str__(self):
        return self.user.username

I tried to add a CustomUser model:

class CustomUser(AbstractUser):
    ROLE_CHOICES = (
        ('admin', 'Admin'),
        ('staff', 'Staff'),
        ('merchant', 'Merchant'),
        ('regular', 'Regular'),
    )
    role = models.CharField(max_length=8, choices=ROLE_CHOICES, default='Regular')

    def is_administrator(self):
        return self.role == 'admin'

    def is_employee(self):
        return self.role == 'staff'

    def is_seller(self):
        return self.role == 'merchant'

But now my login, logout, and registration aren’t working. Any ideas on how to fix this and get the user roles working? Thanks!

Hey RollingThunder! Your project sounds exciting! :smiley:

I’m curious, have you considered using Django’s built-in permissions system instead of creating a custom role field? It might be easier to manage and less likely to break your existing auth setup.

What if you created permission groups for each role (admin, staff, merchant, customer) and then assigned users to those groups? You could then use Django’s @permission_required decorator to control access to different views.

Something like:

from django.contrib.auth.decorators import permission_required

@permission_required('can_access_admin_panel')
def admin_view(request):
    # Your admin view logic here

What do you think about this approach? Have you tried it before?

Also, I’m wondering what specific issues you’re having with login and logout after adding the CustomUser model. Are you getting any error messages? It might help to share those if you have them!

Keep us posted on how it goes! :+1:

hey RollingThunder, looks like ur progress is solid. for user roles, try using django built-in groups. it’s simpler and likely won’t mess auth. just create groups for each role and assign users. then use @user_passes_test decorator for access control. hope this helps!