Model and Permissions

二次信任 提交于 2021-02-18 16:54:25

问题


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

  • create user --> ok
  • login user created --> ok
  • create a new model called 'Article' with title and content as a properties --> ok
  • create several 'Article' instances --> ok
  • I display all the articles at the root of the webapp -->
  • Last step is: in order to manipulate permission, only display some article depending on which user is logged with permissions. like if user A: then display only the article with odd ids (that doesn't make any sence but it's for learning)

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

Cheers


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/30156375/model-and-permissions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!