Deepak Rawat
Deepak Rawat

Reputation: 131

2 models in 1 view and 1 template in Django?

So i have 2 models,

class Post(models.Model):
    topic = models.CharField(max_length=200)
    description = models.TextField()
    created_by = models.ForeignKey(User, related_name='posts')
    created_on = models.DateTimeField()

    def __str__(self):
        return self.topic

class Comment(models.Model):
    commented_by = models.ForeignKey(User, related_name='comments')
    commented_on = models.ForeignKey(Post, related_name='comments')
    commented_text = models.CharField(max_length=500)
    commented_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.commented_text

and i want to display post and comment on single template. So, i created this view:

def post_desc(request, pk):
    post = get_object_or_404(Post, pk=pk)
    comment_list = Comment.objects.all()
    return render(request, 'post_desc.html', {'post': post, 'comment_list':comment_list})

and try to display them in template:

{% if post.created_on %}
  {{ post.created_on }}
{% endif %}
<h1>{{ post.topic }}</h1>
<p>{{ post.description }}</p>

<h4>Comments</h4>
{% if comment_list.commented_on == post.topic %}
  {{ comment_list.commented_by }}{{ comment_list.commented_text }}
{% endif %}

But it is only displaying post and not comment section. What i did wrong here?

Upvotes: 0

Views: 356

Answers (2)

mohammedgqudah
mohammedgqudah

Reputation: 568

the template code is wrong so the view, your view should be like this:

def post_desc(request, pk):
    post = Post.objects.get(id=pk)
    return render(request, 'post_desc.html', {'post': post})

and the template should be

{% for comment in post.comments.all %}
<p>{{comment.text}}</p>
{% endfor %}

Where comments is the related name to access the Comment objects from Post.

Upvotes: 1

Sandeep Balagopal
Sandeep Balagopal

Reputation: 1983

You have to iterate the comments.

{% for comment in comment_list %}
  <do your thing>
{% endfor %}

There is one notable issues in the code.

No need to pass all the comments to template. Only pass the comments that belong to the Post.

Upvotes: 1

Related Questions