【发布时间】:2020-01-23 10:27:28
【问题描述】:
我有这些模型:
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')
在 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/'
他/她可以使用 url 并删除另一个 pk=2 用户的帖子
'authors/2/10/delete/'
我该如何解决这个问题?
【问题讨论】:
-
删除前可以检查
post对象是否属于request.user
标签: django view permissions