0

I'm passing what is necessary for reach the follow function but this is not working for some reason

Error: TypeError at /follow/1/ 

in views.py

def follow(request, pk):
    following, created = Following.objects.get_or_create(
        follow_from_id=request.user,
        follow_to_id=pk)
    return redirect('login')

in models.py

class Following(models.Model):
    follow_from = models.ForeignKey("auth.User",related_name='from_person')
    follow_to = models.ForeignKey("auth.User", related_name='to_person')
    date_follow = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return unicode(self.date_follow)

    def __str__(self):
        return self.date_follow

template

<a href="{% url 'follow' l.pk %}">

in urls.py

url(r'^follow/(?P<pk>\d+)/$', follow, name='follow'),
levi
  • 22,001
  • 7
  • 73
  • 74

2 Answers2

1

follow_from field is a foreign key to the user model. In your filter, you are comparing the ID with an user instance.

Your filter follow_from, should be as it:

follow_from=request.user

But, if you want to compare by id, extract the id from the user instance

follow_from_id=request.user.id
levi
  • 22,001
  • 7
  • 73
  • 74
  • Does this work? The request.user object is still lazy loaded at this stage... (the first part, I agree the second option will work) – nkhumphreys Aug 08 '16 at 18:19
  • @nkhumphreys It's like your answer, django will evaluate it in order to use in the comparation. The same if you request id attribute from request.user, django will be forced to evaluate it. – levi Aug 08 '16 at 18:21
  • that is what I am saying, I dont believe that by using request.user django will evaluate it, it will if you ask for request.user.id but in the first instance you are comparing a foreign key with a SimpleLazyObject – nkhumphreys Aug 08 '16 at 18:22
  • @nkhumphreys django will evaluate it as well. – levi Aug 08 '16 at 18:23
0

This is because request.user object is lazy loaded. Change the lookup to:

def follow(request, pk): following, created = Following.objects.get_or_create( follow_from_id=request.user.id, <------------------------ follow_to_id=pk) return redirect('login')

nkhumphreys
  • 966
  • 7
  • 12