如何在Django视图上定义权限?

时间:2019-09-23 10:59:29

标签: django view permissions

我有以下模型:

class Author(Model):
    user = OneToOneField(User, on_delete=CASCADE)
    # Fields

class Post(Model):
    author = ForeignKey(Author, on_delete=CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()

和一些如下视图:

def authors(request)
   authors = Authors.objects.all()
   return render(request, 'authors.html', {'authors': authors})

作者的视图具有对应的url路径,如下所示:

path('authors/', authors, name='authors')

in authors.html中,我遍历作者,每个作者都有一个链接, 将作者主键发送到作者url并查看:

{% for author in authors%}
    <a href="{% url 'author' author_pk=author.pk %}"{{author.user.email}}</a><br><br>
{% endfor %}

好吧;每个人都可以看到作者列表。

然后我的作者网址路径如下:

path('authors/<int:author_pk>/', author, name='author')
path('authors/<int:author_pk>/<int:post_pk>/delete/', author_delete_post, name='author_delete_post')

我有作者视图,其中显示了每个作者已发布的帖子以及一个删除该按钮的按钮。

def author(request, author_pk)
    author=get_object_or_404(Author, pk=author_pk)
    author_posts = Post.objects.filter(author=author)
    return render(request, 'author.html', {'author_posts': author_posts}

@login_required
def author_delete_post(request, author_pk, post_pk):
    author=get_object_or_404(Author, pk=author_pk)
    author_post = Post.objects.get(author=author, pk=post_pk)  # I know that author=author is redundent but it makes no problem
    author_post.delete()
    return redirect(author, author_pk)

此作者模板:

{% for author_post in author_posts %}
{{author_post.title}}<br>
    {% if user.is_authenticated and author.user == user %}
        <a href="{% url 'author_delete_post' author_pk=author_post.author.pk post_pk=author_post.pk %}">Delete</a><br><br><br>
    {% endif %}

{% endfor %}

我让已登录并在自己页面中的作者可以看到删除按钮。这就像facebook,用户只能删除他/她的帖子,而不能删除其他帖子。

我的问题: 假设有另一个具有pk = 1并已登录。 尽管他/她在此页面中时看不到删除按钮: '/authors/2/' 他/她可以使用该网址并删除另一个具有pk = 2的用户的帖子

'authors/2/10/delete/'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您可以使用request.user检查对象是否属于登录用户

此外,您无需添加author_pk。您可以通过author = get_object_or_404(Author, user=request.user)

与作者联系
@login_required
def author_delete_post(request, post_pk):
    author = get_object_or_404(Author, user=request.user)
    author_post = Post.objects.get(author=author, pk=post_pk)  # I know that author=author is redundent but it makes no problem
    # check if the post belongs to the logged in user
    if author_post.author.user == request.user:
        # delete here
    return redirect(author, author.pk)