0
0
Djangoframework~30 mins

Custom permissions in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Permissions in Django
📖 Scenario: You are building a Django web app where only certain users can edit articles. You want to create a custom permission to control who can update articles.
🎯 Goal: Create a custom permission called can_edit_article and apply it to an Article model. Then check this permission in a view to allow or deny editing.
📋 What You'll Learn
Create an Article model with a title and content fields
Add a custom permission can_edit_article to the Article model
Create a variable user_can_edit that checks if a user has the can_edit_article permission
Use the permission check in a view function to allow editing only if user_can_edit is True
💡 Why This Matters
🌍 Real World
Custom permissions help control who can do what in your web app, like letting only editors update articles.
💼 Career
Understanding custom permissions is important for building secure Django apps and is a common task for backend developers.
Progress0 / 4 steps
1
Create the Article model
Create a Django model called Article with two fields: title as a CharField with max length 100, and content as a TextField.
Django
Need a hint?

Use models.CharField for short text and models.TextField for longer text.

2
Add a custom permission to the Article model
Add a Meta class inside the Article model. Inside Meta, add a permissions list with a tuple ("can_edit_article", "Can edit article").
Django
Need a hint?

The permissions attribute is a list of tuples inside the Meta class.

3
Check the custom permission in a variable
Create a variable called user_can_edit that checks if a user has the permission "app_label.can_edit_article". Use user.has_perm("app_label.can_edit_article"). Replace app_label with the app name blog.
Django
Need a hint?

Use the exact string "blog.can_edit_article" inside has_perm().

4
Use the permission check in a view
In a Django view function called edit_article, use an if statement to check user_can_edit. If True, return HttpResponse("Edit allowed"). Otherwise, return HttpResponseForbidden(). Import HttpResponse and HttpResponseForbidden from django.http.
Django
Need a hint?

Use if user_can_edit: to check permission and return the correct response.