检查用户权限Django

时间:2020-04-30 02:16:32

标签: python django python-3.x django-models

我正在尝试使用Django的默认权限,以仅显示具有博客文章权限的博客文章页面的链接。

精彩的Django文档提供了以下内容:

Assuming you have an application with an app_label foo and a model named Bar, 
to test for basic permissions you should use:

    add: user.has_perm('foo.add_bar')
    change: user.has_perm('foo.change_bar')
    delete: user.has_perm('foo.delete_bar')
    view: user.has_perm('foo.view_bar')

我的应用名为about

这是我的模特:

# models.py
class BlogPost(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(max_length=250, null=True)
    image = models.ImageField(upload_to='blog/main')
    content = HTMLField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    draft = models.BooleanField(default=False)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("post-detail", kwargs={"pk": self.id})

这是我要过滤的HTML

# base.html
          {% if user.has_perm('about.add_blogPost') %}
          <li {% if url_name == 'post' %}class="nav-item active"{% else %}class="nav-item"{% endif %}><a href="{% url 'post' %}" class="nav-link">Add Post</a></li>
          {% endif %}

只要按照文档编写的说明进行操作,就会得到: Could not parse the remainder: '('about.add_blogPost')' from 'user.has_perm('about.add_blogPost')'

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

尝试 {%如果user.has_perm'about.add_blogPost'%}