[Django]-Working with user roles in Django

30👍

You could probably get this to work with django’s built in permissions

That may be more than you need though. A simple solution would just be a UserProfile model with a role field with a OneToOneField to your user:

class UserProfile(models.Model):
  user = models.OneToOneField(User, related_name="profile")
  role = models.CharField()

Set the roles and do checks with the roles in your views:

user.profile.role = "physician"
user.profile.save()

if user.profile.role == "physician":
  #do physician case here

3👍

See here I have a simple solution for you!

If my assumption is right then there will be a admin who will create a user for the application right ?

So for admin make it easy by giving the choices in database and that is the solution.. admin will select roles from the drop down and then your work is done..

You have model for your user so add that fields in user model like this.

here I giving sample code to you


class CreateUser(models.Model):
    ROLES = (

        ('Patient', 'Patient'),
        ('Doctor', 'Doctor'),
        ('Physician', 'Physician'),

    )

    name= models.CharField(max_length=100, null=True)
    last_name= models.CharField(max_length=100, null=True)
    roles = models.CharField(max_length=50, choices = ROLES, null=True)
    date_joined = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.name

Hope this will make your work ….

👤Maddy

Leave a comment