Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 'User' object is not iterable

Tags:

python

django

I don't know why I'm getting this error..

[ 'User' object is not iterable ]

here I want to print (logged in user) followers on the home page. apart from error is my models.py is right ? for followers and following mechanism.

model

class Follow(models.Model):
    following = models.ForeignKey('auth.User', related_name='following')
    followers = models.ForeignKey('auth.User', related_name='followers')

view

def profile(request):
   current_user = request.user
   twi = Follow.objects.get(pk=current_user.id)
   display = twi.followers
   return render(request,'home.html' , 
       {'detail':display,'user':current_user,})

template

{% for o in detail %}
<h1>o.followers</h1>
{% endfor %}
like image 834
Akash D Avatar asked Mar 22 '26 07:03

Akash D


2 Answers

You have a mixup in your logic, your detail refers to followers but the field itself is a link to a singular user, you either need to make this field a ManyToMany relationship, or use a reverse lookup to find what a user follows.

(Theres also a stray comma in your context dict which may cause issues later on..

like image 157
Sayse Avatar answered Mar 24 '26 21:03

Sayse


get returns a single queryset and you cannot iterate over it, if you use get

use this in template

   <h1>{{ detail.followers }}</h1>

or if you need multiple

in view

twi = Follow.objects.filter(pk=current_user.id)

and change this line

display = twi.followers

to

display = twi

and in template

{% for o in detail %}
   <h1>{{ o.followers }}</h1>
{% endfor %}
like image 31
Exprator Avatar answered Mar 24 '26 22:03

Exprator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!