如何在模板中渲染ForeignKey字段?

时间:2017-01-20 01:27:29

标签: python django django-templates django-views

我正在为我的django应用程序制作评论系统,并且我被告知最好制作一个单独的评论投票模型。所以我已经做到了,这就是我的 models.py

    class Comment(models.Model):
        user = models.ForeignKey(User, default=1)
        destination = models.CharField(default='1', max_length=12, blank=True)
        author = models.CharField(max_length=120, blank=True)
        comment_id = models.IntegerField(default=1)
        parent_id = models.IntegerField(default=0)
        comment_text = models.TextField(max_length=350, blank=True)
        timestamp = models.DateTimeField(default=timezone.now, blank=True)

        def __str__(self):
            return self.comment_text


    class CommentScore(models.Model):
        user = models.ForeignKey(User, default=1)
        comment = models.ForeignKey(Comment, related_name='score')
        upvotes = models.IntegerField(default=0)
        downvotes = models.IntegerField(default=0)

        def __str__(self):
            return str(self.comment)

这是我的 views.py ,其中包含了评论的内容:

def article(request, category, id):

    name = resolve(request.path).kwargs['category']
    for a, b in CATEGORY_CHOICES:
        if b == name:
            name = a
            instance = get_object_or_404(Post, id=id, category=name)

    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)


    #comments
    comment = CommentForm(request.POST or None)
    ajax_comment = request.POST.get('text')
    comment_length = len(str(ajax_comment))

    #database_comment = get_object_or_404(Comments, comment_id=1)
    comment_list = Comment.objects.filter(destination=id)
    score = CommentScore.objects.filter(comment=comment_list)

    if request.is_ajax():
        if comment.is_valid():
            comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id)
            print(comment)
            comment.save()

            score = CommentScore.objects.create(comment=comment)
            score.save()
            username = str(request.user)
            return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username})
        else:
            print(comment.errors)

    context = {
        'score': score,
        'comment_list': comment_list,
        'comment': comment,
        'instance': instance,
        'allauth_login': allauth_login,
        'allauth_signup': allauth_signup
    }

    return render(request, 'article.html', context)

因此comment工作正常,但是您可以稍后看到几行,然后尝试创建CommentScore实例以匹配comment。在我的模板中,我已经呈现了每个评论及其字段(comment_textauthor等),但我希望呈现与该upvotes字段相关联的comment字段{1}}。我该怎么做?

模板

{% for i in comment_list %}
    <div class='comment_div'>
        <h3>{{ i.author }}</h3>
        <p>{{ i.comment_text }}</p><br>
    </div>
{% endfor %}

forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment

        fields = [
            'comment_text',
            'id',
            'author',
            'destination',
        ]

1 个答案:

答案 0 :(得分:2)

在你看来,你有这一行:

comment_list = Comment.objects.filter(destination=id)

所以如果你想要转到与CommentScore相关联的Comment,你必须在你的观点上这样写:

score = CommentScore.objects.filter(comment=comment_list)

filter需要多个变量,以便您可以访问模板中的upvotes,如下所示:

{% for i in score %}    
   {{i.upvotes}}
{% endfor %}

如果您有单个score实例,则必须使用get参数:

得分= CommentScore.objects.get(comment = comment_list)

然后你可以

 {{score.upvotes}}
模板上的