0
0
Djangoframework~30 mins

Built-in permission system in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Built-in permission system
📖 Scenario: You are building a simple Django app to manage articles. You want to control who can add, change, or delete articles using Django's built-in permission system.
🎯 Goal: Create a Django model for articles, configure the built-in permission system, and check permissions in a view.
📋 What You'll Learn
Create a Django model named Article with a title and content field
Define a variable user representing the current user
Use Django's built-in permission system to check if user has permission to add an article
Use Django's built-in permission system to check if user has permission to change an article
Use Django's built-in permission system to check if user has permission to delete an article
💡 Why This Matters
🌍 Real World
Many web apps need to control who can add, edit, or delete content. Django's built-in permission system helps manage this easily.
💼 Career
Understanding Django permissions is important for backend developers working on secure web applications.
Progress0 / 4 steps
1
Create the Article model
Create a Django model named Article in models.py with a title field as CharField of max length 100 and a content field as TextField.
Django
Need a hint?

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

2
Set up the user variable
In your Django view file, create a variable named user that represents the current logged-in user by assigning request.user.
Django
Need a hint?

Use request.user to get the current user in a Django view.

3
Check add, change, and delete permissions
Use Django's built-in permission system to check if user has permission to add, change, and delete Article objects. Create three variables: can_add, can_change, and can_delete. Use user.has_perm() with the permission strings 'app_label.add_article', 'app_label.change_article', and 'app_label.delete_article' respectively. Replace app_label with myapp.
Django
Need a hint?

Permission strings follow the pattern 'app_label.action_modelname'.

4
Use permissions to control access
In your Django view, use an if statement to check if can_add is true. If yes, create a variable message with the value 'User can add articles.'. Otherwise, set message to 'User cannot add articles.'.
Django
Need a hint?

Use a simple if statement to set the message based on permission.