Django多对多字段数据渲染 [英] Django many to many field data rendering
问题描述
我想创建一个博客网站,作者和编辑者都可以拥有编辑选项,编辑者将由作者分配。现在我的模型字段如下所示:
I wanted to create a blog site where an author and editor can both have the edit option and the editors will be assigned by author. Now my model field looks like this :
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条件:
then I wanted to check if the person who is accessing if author or editor or not, so I written an if condition :
{% if request.user.author == blogs.author or blogs.editor %}
<a href="#" class="btn btn-warning">Edit</a>
{% endif %}
但不幸的是,每个人都可以访问编辑按钮。我该怎么办?
but unfortunately the edit button can be accessed by everyone. what should I do?
推荐答案
首先。
{% if request.user.author == blogs.author or blogs.editor %}
<a href="#" class="btn btn-warning">Edit</a>
{% endif %}
在这段代码中,条件不是很好定义的。我的建议是采用这种方式:
In this piece of code, the condition is not very good defined. My suggestion is that you make this in this way:
{% if request.user.author == blogs.author or request.user.author == blogs.editor %}
<a href="#" class="btn btn-warning">Edit</a>
{% endif %}
这是一个建议。
现在,另一种可能性是使用JavaScript。
Now another posibility is to use JavaScript.
为此,我为您提供一些自己的代码示例。
In order to do that, I give you some code example of my own.
<script type="text/javascript">
var editor = '{{user.author.editor}}'
if (editor == 'False'){
document.getElementById('edit').innerHTML = ''
}
</script>
在此代码中,我定义的是,如果用户不是编辑者,则不会隐藏该元素(在html),其ID为 edit。因此,在您的模板中,为您的元素设置一个ID。
In this code, I'm defining that if the user is not a editor, I will not hide the element (In html) with id 'edit'. So in your template, set an id to your element.
<a id="edit" href="#" class="btn btn-warning">Edit</a>
为此,您将必须在模型中设置一个布尔字段。
您可以这样操作:
For this, you will have to set a boolean field in your model. You can do it like this:
class Editor(models.Model):
name = models.OneToOneField(Author, on_delete=models.CASCADE, null=True, blank=True)
editor = models.Boolean()
这篇关于Django多对多字段数据渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!