Professional Documents
Culture Documents
Django
Django
Django tip:
You can add custom permissions to a Django model (you still have to enforce it in the
views) 👇
class Post(models.Model):
title = models.CharField(max_length=400)
body = models.TextField()
is_published = models.Boolean(default=False)
class Meta:
permissions = [
(
"set_published_status",
"Can set the status of the post to either publish or not"
)
]
For more, check out Permissions in Django.
django
Posted on Twitter on July 26, 2022.
Django tip:
{% if perms.store.view_inventory %}
{{ all_inventory_items }}
{% endif %}
For more, check out Permissions in Django.
django
Posted on Twitter on July 25, 2022.
Django tip:
@permission_required("blog.view_post")
def post_list_view(request):
return HttpResponse()
For more, check out Permissions in Django.
django
Posted on Twitter on July 24, 2022.
Django tip:
django
Posted on Twitter on July 23, 2022.
Django tip:
Instead of handling permissions for a single user, you can use groups and group-level
permissions 👇
content_type = ContentType.objects.get_for_model(Book)
book_permission = Permission.objects.filter(content_type=content_type)
"""
print(post_permission)
<QuerySet [
<Permission: library | book | Can add book>,
<Permission: library | book | Can change book>,
<Permission: library | book | Can delete book>,
<Permission: library | book | Can view book>
]>
"""
user = User.objects.get(username="librarian_jane_doe")
user.groups.add(librarian_group)
"""
print(user.has_perm("store.add_book")) => False
print(user.has_perm("library.delete_book")) => True
print(user.has_perm("library.change_book")) => True
print(user.has_perm("store.view_book")) => True
"""
For more, check out Permissions in Django.
django
Posted on Twitter on July 22, 2022.
Django tip:
user = User.objects.create_user(
username="test",
password="test",
email="test@user.com"
)
print(user.has_perm("blog.view_post"))
# => False
superuser = User.objects.create_superuser(
username="super",
password="test",
email="super@test.com"
)
print(superuser.has_perm("blog.view_post"))
# => True
For more, check out Permissions in Django.
django
Posted on Twitter on July 21, 2022.
Permissions in Django
Django tip:
{app}.{action}_{model_name}
You can also see (and set) those permissions in the Django admin.
django
Posted on Twitter on July 20, 2022.