Django
Beginner
1 min read
Permissions and Groups
Example
# blog/models.py — custom permissions
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
status = models.CharField(max_length=10, default='draft')
class Meta:
permissions = [
('publish_post', 'Can publish posts'),
('feature_post', 'Can feature posts on the homepage'),
]
# blog/views.py — permission_required decorator
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.mixins import PermissionRequiredMixin
@permission_required('blog.publish_post', raise_exception=True)
def publish_post(request, pk):
post = get_object_or_404(Post, pk=pk)
post.status = 'published'
post.save()
return redirect('blog:post-detail', pk=post.pk)
class PostCreateView(PermissionRequiredMixin, CreateView):
permission_required = 'blog.add_post'
model = Post
form_class = PostForm
template_name = 'blog/post_form.html'
# Creating groups and assigning permissions (e.g., in a management command)
from django.contrib.auth.models import Group, Permission
editors = Group.objects.get_or_create(name='Editors')[0]
publish_perm = Permission.objects.get(codename='publish_post')
editors.permissions.add(publish_perm)
# Assign user to group
user.groups.add(editors)
# Check in templates
# {% if perms.blog.publish_post %}
# <a href="{% url 'blog:publish' pk=post.pk %}">Publish</a>
# {% endif %}
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django