Requesting id in post request returns none

I am trying to build a social media like app in Django using mongo db where users can log in and follow/unfollow each other.

Here is the code for models.py

from django.db import models
import uuid
from datetime import datetime
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model

# Create your models here.

class User(AbstractUser):
    username = models.CharField(max_length=255, unique=True)
    email = models.CharField(max_length=255, unique=True)
    password = models.CharField(max_length=255)

class FollowersCount(models.Model):
    follower = models.CharField(max_length=100)
    user = models.CharField(max_length=100)

Here is the code for views.py

# sign in
class LoginView(APIView):
    def post(self, request):
        email = request.data['email']
        password = request.data['password']

        user = User.objects.filter(email=email).first()

        if user is None:
            raise AuthenticationFailed('User not found!')

        if not user.check_password(password):
            raise AuthenticationFailed('Incorrect password!')

        payload = {
            'id': user.id,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
            'iat': datetime.datetime.utcnow()
        }

        token = jwt.encode(payload, 'secret', algorithm='HS256')

        response = Response()

        response.set_cookie(key='jwt', value=token, httponly=True)
        response.data = {
            'jwt': token
        }
        return response

# logged in user follows / unfollows user based on id 
class FollowView(APIView):
    def post(self, request):
        token = request.COOKIES.get('jwt')

        if not token:
            raise AuthenticationFailed('Unauthenticated!')

        try:
            payload = jwt.decode(token, 'secret', algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('Unauthenticated!')

        follower = User.objects.filter(id=payload['id']).first() 
        print(follower)

        if request.method == 'POST':
            user = request.POST.get('id')
        user_followed = user
        print(user_followed)
        response = Response()

        if FollowersCount.objects.filter(follower=follower, user=user_followed).first():
            delete_follower = FollowersCount.objects.get(follower=follower, user=user_followed)
            delete_follower.delete()
            response.data = {
                'message': str(follower) + ' removed ' + str(user)
            }
            return response 
        else:
            new_follower = FollowersCount.objects.create(follower=follower, user=user_followed)
            new_follower.save()
            response.data = {
                'message': str(follower) + ' followed ' + str(user)
            }
            return response 

However, for the following line of code, when I send a POST request for follow, I am receiving the following error:

if request.method == 'POST':
            user = request.POST.get('id')
        user_followed = user
        print(user_followed)

error:

test05
None
Internal Server Error: /api/follow
Traceback (most recent call last):
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/sparshbohra/reunion2/reunion/server/views.py", line 119, in post
    new_follower.save()
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/base.py", line 740, in save
    force_update=force_update, update_fields=update_fields)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/base.py", line 778, in save_base
    force_update, using, update_fields,
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/base.py", line 859, in _save_table
    forced_update)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/base.py", line 912, in _do_update
    return filtered._update(values) > 0
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/query.py", line 802, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1559, in execute_sql
    cursor = super().execute_sql(result_type)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql
    sql, params = self.as_sql()
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1522, in as_sql
    % (field, val, field.__class__.__name__)
TypeError: Tried to update field server.FollowersCount.follower with a model instance, <User: test05>. Use a value compatible with CharField.
[21/Jan/2023 08:49:21] "POST /api/follow HTTP/1.1" 500 128682

This is what my postman POST request for http://127.0.0.1:8000/api/follow looks like:

{
    "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MiwiZXhwIjoxNjc0MjkxNTI5LCJpYXQiOjE2NzQyODc5Mjl9.SvBHTe5hxuDzWrNeLQJq6JudMo9i6k1GQI-Ndi_ODgg",
    "id": "2"
}

Here, jwt is the token of the loggin in user and id is the user id of the person to be followed. Why is the id of the user to be followed None in the print output to console?

Any help would be appreciated. Pls let me know if you need further info.

You're getting the error here:

new_follower = FollowersCount.objects.create(follower=follower, user=user_followed)
new_follower.save() <----

The question then is, why?

Well, when you take a look at your models, you're using a CharField instead of a ForeignKey to your users:

    follower = models.CharField(max_length=100)
    user = models.CharField(max_length=100)

But, when you try to create a new FollowersCount object, you're passing a User object to follower and user, which is obviously not a value that is compatible with the CharField: hence the error.

You should convert your CharFields to ForeignKeys:

class FollowersCount(models.Model):
    follower = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

Now, when you're creating a new FollowersCount object, it will accept the User objects you're passing to it because now it will be a ForeignKey, and not a CharField.

Back to Top