我如何实现只有帖子的作者才能看到“删除按钮”和“编辑按钮”?
目前我的模板是这样的:
{% if user.is_authenticated %}
<hr>
<a href="{% url 'blog:delete_post' pk=post.pk %}">Delete |</a>
<a href="{% url 'blog:post_update' pk=post.pk %}">Edit</a>
{% endif %}我找到了一个例子,他们用
{% if user.is_authenticated and post.author == request.user%}但是,即使是这篇文章的作者也看不到这两个按钮。我的tempate中的所有其他内容都定义为{{ post.author }}、{{post.title }}等。
我的类帖子有一个外键作者(来自用户)。即使你可以看到按钮,只有真正的作者可以删除帖子,所以视图都是有效的。我唯一纠结的事情就是模板。如果有任何帮助,我将非常高兴!
下面是我在settings.py中的context_processors:
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages'
]下面是我在Post和UserProfile上的模型:
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=200)
content = models.TextField()
class UserProfile(models.Model):
user = models.OneToOneField(User)发布于 2016-03-21 20:52:12
尝试比较主键:
{% if post.author.pk == request.user.pk %}...{% endif %}
https://stackoverflow.com/questions/36129729
复制相似问题