JSRB
JSRB

Reputation: 2613

How to render foreignkey relationship in Django

I have a simple ManyToOne relationship where users can post comments to a poller object.

Comments Model

class Comments(models.Model):
    poller = models.ForeignKey(Pollers, on_delete=models.CASCADE, related_name='comments')
    created_on = models.DateTimeField(auto_now_add=True)
    comment = models.CharField(max_length=250)
    created_by = models.CharField(max_length=80)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Comment {} by {}'.format(self.body, self.name)

The View


def single_poller(request, poller_id):
    """retrieves the item clicked by the user from DB and renders
    the single_poller template for further user interaction
    """

    # Retrieve the item via get
    poller = Pollers.objects.get(poller_id=poller_id)

    # Increase the view field of the object by
    poller.poller_views += 1

    # Save the changed instance and overwrite new view integer
    poller.save()

    # Get the form for comments
    form = CommentsForm

    context = {
        'poller': poller,
        'form': form
    }
    return render(request, 'pollboard/single_poller.html', context)

Now I want to render the comments for each poller into my template like so

<div id="comments-choice-one-wrapper" class="comments-wrapper">
     {{ poller.comments.comment }}
</div>

Somehow it doesn't render the comment I created beforehand. I checked in Django admin if the comment is rly related to the poller and this looks just fine.

Upvotes: 1

Views: 24

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

poller.comments.all is a QuerySet of Comments, so this is a collection, therefore it makes no sense to use .comment since that is an attribute of a Comment object, not an attribute of QuerySet with comments.

You can enumerate over the comments.all, and thus render these comments individually:

<div id="comments-choice-one-wrapper" class="comments-wrapper">
    {% for comment in poller.comments.all %}
        {{ comment.comment }}
    {% endfor %}
</div>

In you Comments model, using self.name or self.body makes not much sense, since that model has no name property or field. You likely should use the __str__ on the Poller:

class Comments(models.Model):
    # ⋮
    
    def __str__(self):
        return f'Comment {self.comment} by {self.poller}'

Note: normally a Django model is given a singular name, so Comment instead of Comments.

Upvotes: 1

Related Questions