0

I am trying to make a friend request class-based-view work on a django project, but keep getting errors. The error I am currently getting is: TypeError at /friend_request/joe int() argument must be a string, a bytes-like object or a number, not 'User'

My Friend model is not looking for an int() though, so I am unsure of what is going on.

class-based view:

class AddFriend(APIView):
    def get(self, request, username):
        friend = User.objects.get(username=username)
        current_user = request.user.username
        f = Friend(current_user, friend, 1)
        f.save()

url:

url(r'^friend_request/(?P<username>[\w.@+-]+)', AddFriend.as_view(), name = 'add_friend'),

model:

class Friend(models.Model):
    #static variables for friend_status attribute
    FRIENDS = 1
    A_REQUESTS_B = 2
    B_REQUESTS_A = 3

    friend_A = models.ForeignKey(User, related_name='friend_A')
    friend_B = models.ForeignKey(User, related_name='friend_B')
    friend_status = models.IntegerField()

    def __str__(self):
        return '%s and %s friendship' % (self.friend_A, self.friend_B)

    class Meta:
        unique_together = (('friend_A', 'friend_B'),)

Ideally this CBV would figure out who the user sending the request is, figre out what friend is being "looked up" in the url, and create/save a new friend instantiation. Where is this int() error coming from, and how do I fix it?

Brian
  • 385
  • 1
  • 5
  • 23
  • 1
    I think this line it's the culprit `f = Friend(current_user, friend, 1)` in the AddFriend APIView. It should be: `f = Friend(friend_A=current_user, friend_B=friend, friend_status=1)` – dorellang Jan 21 '19 at 21:27
  • @dorellang Yes, that fixed this error. Thank you. Do you know why I have to use that syntax? Shouldn't the Friend class just read those variables as arguments without having to specify which arguments they are? – Brian Jan 21 '19 at 21:33
  • 1
    Actually as per the [docs](https://docs.djangoproject.com/en/2.1/ref/models/instances/#django.db.models.Model) you should pass the variables as a keyword argument as I did. That's the way it is I guess, plus I think it's easier to read :P – dorellang Jan 21 '19 at 21:43

0 Answers0