Skip to content Skip to sidebar Skip to footer

Django Rest Framework : "this Field Is Required." With Required=false And Unique_together

I want to save a simple model with Django REST Framework. The only requirement is that UserVote.created_by is set automatically within the perform_create() method. This fails with

Solution 1:

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)

Solution 2:

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

defcreate(self, request, *args, **kwargs):
    request.data.update({'created_by': request.user.id})
    returnsuper(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

Solution 3:

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

@receiver(pre_save, sender=UserVote)defintercept_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']
            breakelse:
        request = None

    instance.pre_save(request)

Then basically you can define pre_save in your model

defpre_save(self, request):
    # do some other stuff# Although it shouldn't happen but handle the case if request is Noneself.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

Solution 4:

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 -

classEmp_UniSerializer( serializers.ModelSerializer ):
    classMeta:
        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."]

Post a Comment for "Django Rest Framework : "this Field Is Required." With Required=false And Unique_together"