Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django object.filter returns Object (1) on search bar

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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 %}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading