Django Groups और Permissions
from django.contrib.auth.models import Group, Permission
group = Group.objects.create(name='group_name')
group.permissions.add(Permission.objects.get(codename='permission_codename'))
user.groups.add(group)
एक Group बनाना
एक Group एक बार बनाया जाता है और फिर reuse किया जाता है — group से attached permissions इसमें हर user पर apply होती हैं।
उदाहरण: Creating a Group
Any user later added to the Editors group automatically gains the change_article permission.
python manage.py shell
>>> from django.contrib.auth.models import Group, Permission
>>> editors = Group.objects.create(name='Editors')
>>> perm = Permission.objects.get(codename='change_article')
>>> editors.permissions.add(perm)
⚠️ Run this in your own terminal or Node.js environment.
एक User को एक Group में जोड़ना
एक बार group मौजूद हो जाने पर, एक user को इसमें assign करना उन्हें group की हर permission grant करता है।
उदाहरण: Adding a User to a Group
alice now inherits every permission attached to the Editors group without any permission being set on her directly.
python manage.py shell
>>> from django.contrib.auth.models import User, Group
>>> alice = User.objects.get(username='alice')
>>> editors = Group.objects.get(name='Editors')
>>> alice.groups.add(editors)
⚠️ Run this in your own terminal or Node.js environment.
Combined Permissions जांचना
has_perm() user को सीधे assigned permissions AND उनके groups से inherited permissions दोनों जांचता है।
उदाहरण: Checking Combined Permissions
This returns True because Alice inherited change_article from the Editors group, even without a direct grant.
python manage.py shell
>>> alice.has_perm('app.change_article')
True
⚠️ Run this in your own terminal or Node.js environment.
- हर user को individually permissions assign करना बजाय एक Group एक बार बनाने और users को इसमें जोड़ने के।
- यह भूल जाना कि किसी model की default add/change/delete/view permissions migrations run होने के बाद ही auto-create होती हैं।
is_staff(जो/admin/में log in कर सके) को असली model permissions रखने से confuse करना — सिर्फ staff status permissions नहीं देता।
- Groups कई permissions को साथ bundle करते हैं ताकि इन्हें एक साथ कई users को assign किया जा सके।
- Django हर model के लिए add/change/delete/view permissions auto-create करता है।
- user.groups.add(group) एक user को एक group में assign करता है; user.has_perm(...) उनकी combined permissions जांचता है।
- Groups के through permissions manage करना per-user assign करने से बेहतर scale करता है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Introduction to Django's Auth System
- The User Model Overview
- Setting Up a Login View
- Logout Functionality
- User Registration Form
- The login_required Decorator
- The permission_required Decorator
- Django Groups and Permissions
- Password Hashing in Django
- Session Authentication Basics
- Introduction to Custom User Models
- Sending Emails with Django