Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean Field always saving False django

I am using Django Rest Framework, when the payload comes from post request i have a boolean field of company_status, this field is true but when the user saves it becomes False, I can't get what the problem is:

views.py

class CreateUser(APIView):

    def get(self,request):
        return Response([UserSerializer(dat).data for dat in User.objects.all()])

    def post(self,request):
        payload=request.data
        serializer = UserSerializer(data=payload) 
        print(payload)  # here it shows company_status True
        if serializer.is_valid():
            instance = serializer.save()
            instance.set_password(instance.password)
            instance.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','user_image','designation','company_status','age','gender']

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        return user

    def update(self, instance, validated_data):
        for k, v in validated_data.items():
            setattr(instance, k, v)
            instance.save()
        return instance

models.py

class User(AbstractBaseUser,PermissionsMixin):

    # is_admin=models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    first_name = models.CharField(max_length=30, blank=True)
    last_name = models.CharField(max_length=30, blank=True)
    date_joined = models.DateTimeField(null=True, blank=True)
    user_image=models.ImageField(upload_to=user_main_image_directory_path,null=True,blank=True)
    username = models.CharField(

        max_length=150,
        unique=True,
        null=True,

    )
    is_active = models.BooleanField(default=True)
    phonenumber=models.CharField(max_length=13,default="null")
    faceid=HashidField
    is_booker=models.BooleanField(default=False)
    designation=models.CharField(max_length=30,null=True)
    company_status=models.BooleanField(null=True,blank=True)  # this is the field
    object = UserManager()
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []
    age=models.IntegerField(null=True)
    gender=models.CharField(max_length=10,null=True,blank=True)

response

Response:

        "id": 1,
        "username": "nabeel",
        "user_image": "/media/1/opencv_frame_0.jpg",
        "designation": "bscs",
        "company_status": false,
        "age": 23,
        "gender": "male"
    }

Request payload

Request payload:
payload={
age:25
company_statu:true
designation:bscs
gender:male
password:manofsteel#2
username:xyz
}

Can't get why it always save False in company_status, I have printed the payload comes from post request and it show True,but when serializer saves it shows false

like image 396
Nabeel Ayub Avatar asked Sep 18 '26 01:09

Nabeel Ayub


1 Answers

First, I recommend you to modify your serializer to check whether serializer recieves company_status. To make it change as the following:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','user_image','designation','company_status','age','gender']
        extra_kwargs = dict(company_status=dict(required=True, allow_null=False))

    def create(self, validated_data):
        user = User.objects.create(**validated_data)
        return user

    def update(self, instance, validated_data):
        for k, v in validated_data.items():
            setattr(instance, k, v)
            instance.save()
        return instance

If serializer raises ValidationError, then most probably your serializer can not understand the request.data and thus, can not deserialize properly. Here you have to look at your React code whether it is sending with content-type:application/json in request header.

Second, if it is not the case, check your model migrations, maybe in the beginning you had boolean field with default=False and then you have made changes, but forgot to migrate the changes.

Third, even if it does not help, then maybe the problem is even deeper inside at the lowest level of your database configuration if you made some changes to your database settings before.

Even if it is not the case, then I am really sorry to tell you that you have messed up with your project settings.

like image 163
Bedilbek Avatar answered Sep 20 '26 15:09

Bedilbek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!