0👍
Django already allows for a Group, User permissions which we can customize for our needs.
-
Create the groups you need (form the admin panel for example, or by following this SO post.):
- ‘country-admin-group`
- ‘state-admin-group’
- ‘user-group’
-
Create custom permissions for your user groups and add them accordingly:
from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType from your_app_name.models import CustomUserModel ct = ContentType.objects.get_for_model(CustomUserModel) permission_sl = Permission.objects.create( codename='can_add_sl_user', name='Can add SL user', content_type=ct ) permission_user = Permission.objects.create( codename='can_add_simple_user', name='Can add simple user', content_type=ct ) ... cl_group = Groups.get(name='country-admin-group') cl_group.permissions.add(permission_sl) cl_group,permissions.add(permission_user) sl_group = Groups.get(name='state-admin-group') sl_group,permissions.add(permission_user) ...
-
Create views (and the corresponding urls) for each type of user.
Personally I prefer to use class based views when applicable. We will control the access to each view with themethod_decorator
andpermission_required
decorators:from django.http import HttpResponse from django.views import View class CountryAdminView(View): @login_required def list(self, request): """ Can access only users created by him """ content = Users.objects.filter(parent_id=request.user.id) return HttpResponse(content) @method_decorator(@permission_required('your_app_name.can_add_sl_user')) def create(self, request): ... Logic for creating an SL admin user. ...
Keep in mind that the above is a simplified example to set you in the path to the solution.
As @BurhanKhalid points out, you can skip a part of the above by using django-guardian.
You can also use django-role-permissions to define per user roles and add permissions to those roles.