So I have a Django website Project that contains a database of all the different books stored in it. With my search bar, if I type in the name it will show results from the database. The problem is that whenever I type in said name (One Piece or Attack On Titan), instead of showing its title name, it will either show Book Object (1) or Book Object (2) depending on what name I type and I don't know why.
This is where I defined my classes:
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
editor = models.CharField(max_length=255)
year_published = models.IntegerField()
number_in_stock = models.IntegerField()
daily_rate = models.FloatField(null=True)
genre = models.ForeignKey(Genre, on_delete=models.CASCADE)
date_created = models.DateTimeField(default=timezone.now)
manga_image = models.ImageField(null=True, blank=True, upload_to='images/')
And this is where I defined my requests:
def search_manga(request):
if request.method == "POST":
searched = request.POST[('searched')]
mangas = Book.objects.filter(title__contains=searched)
return render(request, 'books/search_manga.html', {'searched': searched, 'mangas': mangas})
else:
return render(request,'books/search_manga.html', {})
Also this is the HTML document I'm trying to show the results on:
{% extends 'base.html' %}
{% block content %}
<style>
h1 {
text-align: center;
}
</style>
{% if searched %}
<h1>You Searched For {{searched}}</h1>
<br/>
{% for manga in mangas %}
{{ manga }}<br/>
{% endfor %}
{% else %}
<h1>Hey! You Forgot To Search For A Manga</h1>
{% endif %}
{% endblock %}
Please note I'm very new to Django by the way.
CodePudding user response:
Your render()
method is returning a QuerySet of Books (mangas
) to the template. You need to iterate over this set of books, and render the attributes you care about in your template like so:
{% for x in mangas %}
name is {{ x.title }}
{% endfor %}