Search code examples
djangodjango-modelsdjango-authenticationdjango-users

How to extend Django User model to manage permissions


I am working on a web-app using Django 1.3 and Python2.6. I have to extend the Django User model such that there are three types of users and manage permissions for each type.

To elucidate, say there are three types of Users: Faculty, TAs and Students. TAs will be able to create a new 'Assignment', Faculty will be able to 'review' and confirm it, Students 'submit' Solutions, which Faculty will have to 'review' and TAs finally can check those 'reviewed' Solutions. Now there are three types of users: TAs who can create Assigments and grade Solutions, Faculty who can review Assignments and Solutions to confirm them, and Students who can submit Solutions.

Now, I understand that there are two ways to extend a User model. I can create a UserProfile and add a field called 'user_type'. Other way is to subclass the User model. I think sub-classing is a better approach coz there are fields which vary for different type of users.

I will have a single login form, but can have different registration forms for different types of users. Why would you choose either of the approaches?

I understand that the best way to manage permissions for different types of users is through User Groups. How to create groups, check if the user belongs to a group? Does the choice of how to extend the User model effect the way I manage permissions?


Solution

  • If you create a subclass, the main class will be instantiated automatically, so it's more convenient. If you make a profile class, you'll need to instantiate manually both of the classes.

    For simple cases you might need to just check the user type before allowing actions. You may use the buildt-in permissions backends of Django.

    Whether you subclass or make a profile class, does not affect much the groups workflow. There will always be a ManyToMany relation between groups and users. But it's better to make it between User and Group classes than, say, between UserProfile and Group.

    If you plan a bigger project, I can give a brief description of what a permission framework has to define:

    • subject (the user or group trying to create, access or edit something)
    • object (the target of the action)
    • owner (the owner of the object)
    • role (the relationship between the subject and the object or the object's owner)
    • permission (the rule defining what roles are allowed to do what actions)