Working with user roles in Django

时间:2015-10-30 21:40:25

标签: python django django-users user-roles multiple-users

I have some question In a project I have the need of work with users which are of three (may be more) types of them have different roles: physician patient administrator

I have been thinking use of the Django Model Users and extend it creating a userprofile model ... But I ignore how to manage the different roles because, the userprofile model will have fields of the user model, althought I don't know how to address the roles topic.

1 User have Many userprofiles may be? I don't know

Or may be I will should create a Roles Model/Table in where I specify the roles types and create a relation with the Users Model. This is a good possibility.

Another possibility (as a comment more below) is check the Django permissions system, in which I can create user groups, and assign permissions to these groups, althought here I can only edit, create and delete models really?

I am a few confuse about of how to address this subject

Searching I found this app. https://github.com/dabapps/django-user-roles

If somebody can orient me about it, I will be much grateful Best Regards

2 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分:0)

看到这里,我为您提供了一个简单的解决方案!

如果我的假设正确,那么将有一位管理员为该应用程序创建用户吗?

因此,对于管理员来说,可以通过在数据库中提供选择来简化操作,这就是解决方案。.管理员将从下拉菜单中选择角色,然后完成您的工作。.

您已经为用户建立了模型,因此可以在用户模型中添加该字段。

在这里,我给您示例代码


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

希望这会使您工作....