Make BooleanField necessary in the Django Rest Framework

I have a model with a boolean field that I would like to deserialize using the Django rest framework, and I want a complaint serializer when there is no field in the mail request. But this is not so. He silently interprets the missing logical value as False.

class UserProfile(models.Model): """ Message between two users """ user = models.OneToOneField(User, verbose_name="django authentication user", related_name='user_profile') newsletter = models.BooleanField(null=False) research = models.BooleanField(null=False) 

A model is created using Serialiser as follows:

  class UserProfileSerializer(serializers.ModelSerializer): research = BooleanField(source='research', required=True) newsletter = BooleanField(source='newsletter', required=True) class Meta: model = UserProfile fields = ('research', 'newsletter') 

In my opinion, I also create a user, so I have a few steps:

  def post(self, request, format=None): userprofile_serializer = UserProfileSerializer(data=request.DATA) reg_serializer = RegistrationSerializer(data=request.DATA) phone_serializer = PhoneSerializer(data=request.DATA) errors = {} if userprofile_serializer.is_valid() and reg_serializer.is_valid() and phone_serializer.is_valid(): user = reg_serializer.save() data = reg_serializer.data user_profile = userprofile_serializer.object user_profile.user = user userprofile_serializer.save() return Response(data, status=status.HTTP_201_CREATED) errors.update(reg_serializer.errors) # ... return Response(errors, status=status.HTTP_400_BAD_REQUEST) 

However, the following test script fails because there is no complaint about the missing parameter in the rest of the structure, but instead inserts False from from_native

  def test_error_missing_flag(self): data = {'username': "test", 'password': "123test", 'email': ' test@me.com ', 'newsletter': 'true', 'uuid': self.uuid} response = self.client.post(reverse('app_register'), data) # should complain that 'research' is not found self.assertTrue('research' in response.data) 

If I replace the "research" field with the Integer field, the serializer will fail with the error as expected. Any ideas?

+4
source share
1 answer

There was a problem with boolean fields and the required argument. It should now be fixed in master.

See this problem: https://github.com/tomchristie/django-rest-framework/issues/1004

+2
source

Source: https://habr.com/ru/post/1499138/


All Articles