获取模板中另一个孩子的数据

时间:2018-06-29 08:56:51

标签: python django django-templates

我正在建立一个可以发表评论的董事会。

所有功能都能正常工作。

但是我唯一需要的是显示评论作者的个人资料。

{{ board.title }}
{{ board.text }}

{% for comment is context.commentmodel_set.all %}
    {{ comment.comment }}
    {{ comment.whose.profile??? }} <- ????
{% endfor %}

//////////////编辑[添加模型] ////////////

# Appname : board / model
class Board(models.Model):
    whose = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField()
    text = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Comment(models.Model):
    post = models.ForeignKey(Board, on_delete=models.CASCADE)
    whose = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    comment = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


# Appname : accounts / model
class Profile(models.Model):
    whose = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    i_need = models.CharField()
    address = models.CharField()
    tel = models.CharField()

//////编辑第二个[Views.comment] //////

@login_required
def comment(request, pk):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.post = Board.objects.get(pk=pk)
            post.whose = request.user
            post.save()
            return redirect('board_detail', pk)
        else:
            print('TurminalCheck : Invalid!!')
    else:
        form = CommentForm()

    context = {
        'form': form,
    }
    return render(request, 'boardapp/board.html', context)

下面提供参考图像。 enter image description here

1 个答案:

答案 0 :(得分:1)

您应该在个人资料模型中添加其字段的相关名称

class Profile(models.Model):
    whose = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile")
    i_need = models.CharField()
    address = models.CharField()
    tel = models.CharField()

在您可以使用{{comment.whose.profile}}呼叫个人资料之后