[Django]-Django REST Framework : "This field is required." with required=False and unique_together

12πŸ‘

βœ…

I had a similar problem and I solved it by explicitly creating and passing a new instance to the serializer. In the UserVoteViewSet you have to substitute perform_create with create:

 def create(self, request, *args, **kwargs):
    uv = UserVote(created_by=self.request.user)
    serializer = self.serializer_class(uv, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
πŸ‘€SimoV8

7πŸ‘

I was able to solve this with one-liner in views.py

def create(self, request, *args, **kwargs):
    request.data.update({'created_by': request.user.id})
    return super(UserVoteViewSet, self).create(request, *args, **kwargs)

Since this view expects user to be authenticated, don’t forget to extend permission_classes for rest_framework.permissions.IsAuthenticated

πŸ‘€SukiCZ

2πŸ‘

The other weird way you can do is use signals like this

@receiver(pre_save, sender=UserVote)
def intercept_UserVote(sender, instance, *args, **kwargs):
    import inspect
    for frame_record in inspect.stack():
        if frame_record[3]=='get_response':
            request = frame_record[0].f_locals['request']
            break
    else:
        request = None

    instance.pre_save(request)

Then basically you can define pre_save in your model

def pre_save(self, request):
    # do some other stuff
    # Although it shouldn't happen but handle the case if request is None
    self.created_by = request.user

The advantage of this system is you can use same bit of code for every model. If you need to change anything just change in pre_save(). You can add more stuff as well

πŸ‘€Mirage

0πŸ‘

Add the following to the ViewSet:

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

And the following on the Serializer:

class Meta:
    extra_kwargs = {
        'user': {
            'required': False,
        },
    } 
πŸ‘€Andre Pereira

-1πŸ‘

Below code worked for me.

Even I was facing same error after many experiments found something, so added all fields in serializer.py in class meta, as shown below –

class Emp_UniSerializer( serializers.ModelSerializer ):
    class Meta:
        model = table
        fields = '__all__'  # To fetch For All Fields
        extra_kwargs = {'std_code': {'required': False},'uni_code': {'required': False},'last_name': {'required': False},'first_name': {'required': False}}

Here, we can update any field which are in "extra_kwargs", it wont show error ["This field is required."]

πŸ‘€Omkar

Leave a comment