BenNG
BenNG

Reputation: 531

Model and Permissions

I'm currently learning python/django As a Tutorial for myself I have done that:

It seems to be very complicated to do 'permission by instance' by hand right ?

Cheers

Upvotes: 4

Views: 14473

Answers (2)

Fanis Despoudis
Fanis Despoudis

Reputation: 386

When you say 'I need permission by instance' probably you mean 'I need to use django-guardian' https://django-guardian.readthedocs.org/en/stable/

Upvotes: -2

BenNG
BenNG

Reputation: 531

First we have to create our 2 permissions

from django.db import models

class Article(models.Model):
    title = models.TextField()
    content = models.TextField()

    class Meta:
        permissions = (
            ('can_view_odd_ids', 'can_view_odd_ids'),
            ('can_view_even_ids', 'can_view_even_ids'),
        )

    def __str__(self):
        return self.title

after running the migration, we can manually apply the permission to our users using the shell

odd_even = Permission.objects.get(name='can_view_even_ids')
user_yui = User.objects.get(username='yui')
user_yui.user_permissions.add(odd_even)
user_yui.save()

and then test in the view the permission on our users (something like that)

def my_view(request):
    data = {}
    if request.user.is_authenticated():
        count = Article.objects.all().count()
        if request.user.has_perm("account.can_view_odd_ids"):
            data = {'articles': Article.objects.all()[1::2]})
        elif request.user.has_perm("account.can_view_even_ids"):
            data = {'articles': Article.objects.all()[0::2]})
    return render(request, 'index.html', data)

Upvotes: 9

Related Questions