john
john

Reputation: 557

DJANGO,DRF:request id returning a NONE value instead the user object

i want to create a follower option in django using DRF so here my models.py

class Connect(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, unique = True, related_name = 'rel_from_set',on_delete=models.CASCADE)
    following = models.ManyToManyField(settings.AUTH_USER_MODEL,  related_name = 'follwed_by')
    def __str__(self):
        return str(self.following.all().count())

urls.py

url(r'^conn/(?P<id>\d+)', ConnectApi),

serializer.py

class ConnectSerializer(serializers.ModelSerializer):
    class Meta:
        model=Connect
        fields=('user','following')

views.py

@api_view(['GET','POST'])
def ConnectApi(request,id):
    user_id=request.POST.get('id')
    print(user_id)
    # user_id=request.GET['id']
    # action=request.POST.get('action')
    if user_id :
    # if user_id and action:

        try:
            user1=User.objects.get(id=user_id)
            if user1 :
                Connect.objects.get_or_create(user=request.user,
                                                following=user1)
            else:
                Connect.objects.filter(user=request.user,
                                        following=user).delete()
            return JsonResponse({'status':'ok'})
        except:
            return JsonResponse({'status':'ki'})
    return JsonResponse({'status':'ko'})

but whenever i fired up the url

http://127.0.0.1:8000/connect/conn/2

this is the response

{"status": "ko"}

and in the terminal i could see "NONE " for print(user_id) command

i don't understand where i have done the mistake and i dont think if this is the best practice to make followers function if you know one please let me know

Upvotes: 1

Views: 394

Answers (1)

JPG
JPG

Reputation: 88689

You are passing the id through url and it's directly available inside the view function. So, you don't want to query it from somewhere else

So, use this,


@api_view(['GET', 'POST'])
def ConnectApi(request, id):
    user_id = id
    print(user_id)
    # your code

Upvotes: 1

Related Questions