Django ForaignKey attribute not showing up in html
So, i have some models and connected each other. And in my views i get chapter model ordered by date published, then remove the ones with same manga(foraign key associated with other model). But apperantly accept for the fields not connected with anything i can't acces the models fields. But also because i am working with a quaryset i cant sort by id or anything, also have to acces the manga models fields associated with chapter. but it does not show up in html. how can i do it ?
my models :
class Manga(models.Model):
manga_name = models.CharField(max_length= 255, default="null")
manga_image = models.ImageField(upload_to="thumbnail", default="thumbnail/noimage.png")
manga_views=models.IntegerField(default=0)
def __str__(self):
return f"{self.id}, {self.manga_name}"
class Fansub(models.Model):
fansub_name = models.CharField(max_length=255, default="null")
def __str__(self):
return f"{self.id}, {self.fansub_name}"
class Chapter(models.Model):
chapter_number = models.IntegerField(default=0)
chapter_url = models.URLField(default="www.example.com")
manga = models.ForeignKey(Manga, on_delete=models.CASCADE)
fansub = models.ForeignKey(Fansub, on_delete= models.CASCADE)
relase_date= models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"{self.chapter_number}, {self.manga}, {self.fansub}"
my view :
def Index(request):
manga = Manga.objects.all()
chapter = Chapter.objects.all().values()
fansub = Fansub.objects.all().values()
mostview = manga.order_by("-manga_views")[:5]
relasedateorder = chapter.order_by("relase_date")
context= {
"Manga": manga,
"Chapter": chapter,
"Fansub": fansub,
"Mostview": mostview,
"LastUpdated": relasedateorder,
}
template = loader.get_template("Index.html")
and finnaly the html:
{%for d in LastUpdated%}
<p>{{d.manga}}</p>
{%endfor%}
In your view, you're using the values method on the Chapter queryset, which returns a queryset of dictionaries instead of Chapter objects. To access the associated Manga object, you need to change your view to return a queryset of Chapter objects like this:
def Index(request):
manga = Manga.objects.all()
chapter = Chapter.objects.all().order_by("relase_date")
fansub = Fansub.objects.all().values()
mostview = manga.order_by("-manga_views")[:5]
context= {
"Manga": manga,
"Chapter": chapter,
"Fansub": fansub,
"Mostview": mostview,
}
template = loader.get_template("Index.html")
#HTML
{% for chapter in Chapter %}
<p>{{chapter.manga.manga_name}}</p>
{% endfor %}
You can access the all the instances of Manga
model associated with chapter
instance by using _set
as suffix in the following way:
{% for i in LastUpdated %}
<p>{{i.chapter_number}}</p>
<h2> manga model attributes below</h2>
{% for j in i.manga_set.all %}
{{j.manga_name}}
{{j.manga_views}}
{% endfor %}
{% endfor %}
Also you should use Chapter.objects.all().order_by("relase_date")
this queryset as using .values()
gives you a key-value pair (dict).