Home > Software design >  django AttributeError when querying data from the database
django AttributeError when querying data from the database

Time:06-27

I keep getting AttributeError: 'QuerySet' object has no attribute 'title' error whenever i use obj=Userpost.objects.all() . How will i format it so that i can use it to query all data in the database? this is my snippet code

    obj=Userpost.objects.all()
context={
'title':obj.title,
'content':obj.content,
'date':obj.date,

}

CodePudding user response:

You are approaching it in the wrong way. Your obj is a QuerySet object, so basically it contains many object. You are probably thinking that you are passing attributes of every single object, but actually you are trying to get such attributes from QuerySet.

Change it to:

posts = Userpost.objects.all()
context = {
    'posts': posts
}

Then in template:

{% for post in posts %}
    {{ post.title }}
    {{ post.content }}
    {{ post.date }}
{% endfor %}
  • Related