【问题标题】:Django many to many field data renderingDjango多对多字段数据渲染
【发布时间】:2020-12-22 13:57:05
【问题描述】:

我想创建一个博客站点,其中作者和编辑都可以拥有编辑选项,并且编辑将由作者指定。现在我的模型字段如下所示:

class Editor(models.Model):

name = models.OneToOneField(Author, on_delete=models.CASCADE, null=True, blank=True)


class Blog(models.Model):


title = models.CharField(max_length=150, null=True, blank=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True)
editor = models.ManyToManyField(Editor, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
article = models.TextField(blank=True, null=True)
genre = models.ManyToManyField(Genre, blank=True)


def __str__(self):
    return self.title

和views.py:

def blog(request, pk):


if request.user.is_authenticated:
    blogs = Blog.objects.get(id=pk) //for dynamic url
    editors = Editor.objects.all()

context = {'blogs':blogs,'editors':editors}
return render(request, 'blog/blog.html', context)

然后我想检查访问的人是否是作者或编辑,所以我写了一个 if 条件:

{% if request.user.author == blogs.author or blogs.editor %}
<a href="#" class="btn btn-warning">Edit</a>
{% endif %}

但不幸的是,每个人都可以访问编辑按钮。我该怎么办?

【问题讨论】:

    标签: html sqlite django-models django-views django-templates


    【解决方案1】:

    首先。

    {% if request.user.author == blogs.author or blogs.editor %}
    <a href="#" class="btn btn-warning">Edit</a>
    {% endif %}
    

    在这段代码中,条件没有很好地定义。我的建议是你这样做:

    {% if request.user.author == blogs.author or request.user.author == blogs.editor %}
    <a href="#" class="btn btn-warning">Edit</a>
    {% endif %}
    

    这是一个建议。

    现在另一种可能性是使用 JavaScript。

    为了做到这一点,我给你一些我自己的代码示例。

    <script type="text/javascript">
            var editor = '{{user.author.editor}}'
    
            if (editor == 'False'){
                document.getElementById('edit').innerHTML = ''
            }
    </script>
    

    在这段代码中,我定义如果用户不是编辑器,我将不会隐藏 id 为“edit”的元素(在 html 中)。因此,在您的模板中,为您的元素设置一个 id。

    <a id="edit" href="#" class="btn btn-warning">Edit</a>
    

    为此,您必须在模型中设置一个布尔字段。 你可以这样做:

    class Editor(models.Model):
    
     name = models.OneToOneField(Author, on_delete=models.CASCADE, null=True, blank=True)
     editor = models.Boolean()
    

    【讨论】:

    • 我忘了说javascript代码应该在你的模板中,最后。
    • "在这段代码中,我定义如果用户不是编辑器,我不会隐藏 id 为 'edit' 的元素(在 html 中)。" ——我想我实际上要求的是相反的。如果用户是这个博客的编辑,应该会出现编辑按钮。
    • 另一件事是一个作者可以有多个博客编辑,每个编辑也可以有自己的文章和编辑。我已经问过another_question_regarding_this,请看一下。
    • 我错了...我的意思是如果用户不是编辑器,我会隐藏元素。但是好的,我认为改变你需要的逻辑并不难,我只是给你一些你能做什么的例子。有无数种方法可以做到这一点
    • 稍后我会检查您的其他帖子。如果我对这篇文章的回答有帮助,请标记它
    猜你喜欢
    • 2019-09-27
    • 2020-12-18
    • 2013-04-27
    • 1970-01-01
    • 2018-05-20
    • 2011-02-05
    • 2021-11-20
    • 2016-02-23
    相关资源
    最近更新 更多