django-permission AuthorPermissionLogic 在基于函数的视图中不起作用

django-permission AuthorPermissionLogic not working in function based view

正在使用 django-permission on simple test app (almost identical to the example used in the docs) to try to figure out how it works. I have read the documentation and tried to use the example app provided on this link

问题是文章的作者无法编辑/删除文章。

相关用户已被授予管理部分的所有权限。

下面列出了关键代码 - 非常感谢任何帮助

test_app/models.py

class Article(models.Model):
    created_by = models.ForeignKey(User)
    created = models.DateField(auto_now_add=True)
    modified = models.DateField(auto_now=True)
    title = models.CharField(max_length=100)
    content = models.TextField()

    class Meta:
        app_label = 'test_app'

from permission import add_permission_logic
from permission.logics import AuthorPermissionLogic

add_permission_logic(Article, AuthorPermissionLogic(
    field_name='created_by',
    any_permission = False,
    change_permission = True,
    delete_permission = True,
))

test_app/views.py

@permission_required('change_article')
def change_article(request, *args, **kwargs):
    pk = kwargs.pop('pk')
    template = 'test_app/edit.html'
    article = models.Article.objects.get(id=pk)

    if request.method == 'POST':
        form = forms.Article_form(request.POST, instance=article)

        if form.is_valid():
            article = form.save(commit=False)

            article.created_by = request.user
            article.title = form.cleaned_data['title']
            article.content = form.cleaned_data['content']

            article.save()

            return HttpResponseRedirect('/test/')

        else:

            raise Http404

    else:
        form = forms.Article_form(instance=article)

        return render(request, template_name=template, context={'form':form})

test_app/perms.py

PERMISSION_LOGICS = (
    ('test_app.Article', AuthorPermissionLogic()),
)

编辑

最后,这个 link 上的项目 Github 页面有更长的讨论。

虽然问题的 objective 已解决 - 事实证明该函数本身是一个容易出现意外行为的遗留函数。项目所有者的建议是使用基于 class 的视图而不是基于函数的视图。

我不太明白

The user in question has been granted all permissions in the admin section.

的意思是(不确定 "admin section" 是什么)但是

  1. 您不需要 perms.py,而您已经在 models.py.

  2. 中添加了权限逻辑
  3. 您需要使用 test_app.change_article 代替 (<app_label>.<perm>_<model_name>)

顺便说一下,虽然您不需要 perms.py 所以没关系,但是 perms.pyAuthorPermissionLogic 的实例在您没有指定的情况下未正确配置field_name 那里(field_name 的默认值是 'author' 如果你不指定。) https://github.com/lambdalisue/django-permission/blob/master/src/permission/conf.py#L24