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

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

# sign in
class LoginView(APIView):
    def post(self, request):
        email =['email']
        password =['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 = {
            '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) = {
            '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!')

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

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

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

        if FollowersCount.objects.filter(follower=follower, user=user_followed).first():
            delete_follower = FollowersCount.objects.get(follower=follower, user=user_followed)
   = {
                'message': str(follower) + ' removed ' + str(user)
            return response 
            new_follower = FollowersCount.objects.create(follower=follower, user=user_followed)
   = {
                '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


Internal Server Error: /api/follow
Traceback (most recent call last):
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/core/handlers/", line 47, in inner
    response = get_response(request)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/core/handlers/", 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/", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/views/generic/", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/", line 469, in handle_exception
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/", line 480, in raise_uncaught_exception
    raise exc
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/rest_framework/", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/sparshbohra/reunion2/reunion/server/", line 119, in post
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/", 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/", line 778, in save_base
    force_update, using, update_fields,
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/", line 859, in _save_table
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/", line 912, in _do_update
    return filtered._update(values) > 0
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/", 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/", 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/", line 1162, in execute_sql
    sql, params = self.as_sql()
  File "/Users/sparshbohra/reunion2/venv/lib/python3.7/site-packages/django/db/models/sql/", 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 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) <----

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