I have a created two models in my models.py
file. I have also created a view and that view renders a template named index.html
. I want to show the post and it's likes count in my index webpage/template. but the below code doesn't work.
models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=42)
author = models.ForiegnKey(User, on_delete=models.CASCADE, related_name='author_user')
create_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'{self.author.first_name} {self.author.last_name}'
class Like(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='liked_post')
user = models.Foreignkey(User, on_delete=models.CASCADE, related_name='post_liked_by')
def __str__(self):
return f'{self.user.username}@{self.post.title}'
views.py
from django.shortcuts import render
from .models import *
def index(request):
posts = Post.objects.all()
likes = Like.objects.all()
context = {
'posts': posts,
'likes': likes,
}
return render(request, 'index.html', context)
index.html
<html>
<head>
<title>
Home
</title>
</head>
<body>
{% for post in posts %}
<h1>
{{ post.title }}
</h1>
<p>
Author: {{ post.author.first_name }} {{ post.author.last_name }}
</p>
<p>
Date Created: {{ post.create_date }}
</p>
<p>
<i class="fa fa-heart"></i>
{{len(likes)}}
</p>
{% endfor %}
</body>
</html>
thank you in advance.