0

I'm trying to overwrite the value of the DateField field if it's empty. As usual, a field with this type is not validated during serialization if the value is not an object of datetime class. I need to write null to the database if the value is empty. To do this, I'm trying to change the clean() model method.

serializer.py

class VendorsSerializer(serializers.ModelSerializer):
    contacts = VendorContactSerializer(many=True)

    class Meta:
        model = Vendors
        fields = (...
                  'nda',
                  'contacts',)


    def create(self, validated_data):
        contact_data = validated_data.pop('contacts')
        vendor = Vendors.objects.create(**validated_data)
        vendor.full_clean()
        for data in contact_data:
            VendorContacts.objects.create(vendor=vendor, **data)
        return vendor

models.py

class Vendors(models.Model):
    ...
    nda = models.DateField(blank=True, null=True)

        def clean(self):
        if self.nda == "":
            self.nda = None

view.py

class VendorsCreateView(APIView):
    """Create new vendor instances from form"""
    permission_classes = (permissions.AllowAny,)
    serializer_class = VendorsSerializer

    def post(self, request, *args, **kwargs):
        serializer = VendorsSerializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            serializer.save()
        except ValidationError:
            return Response({"errors": (serializer.errors,)},
                            status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(request.data, status=status.HTTP_200_OK)

Why clean() doesnt run ?

json

{
    "vendor_name": "The Greey swAlsbudam2",
    "country": "Belgium",
    "nda": "",
    "contacts": [{"contact_name": "Mrk", "phone": "2373823", "email": "[email protected]"},
            {
            "contact_name": "Uio",
            "phone": "34567",
            "email": "[email protected]"
        }
    ]


}

1 Answer 1

1

Because you are creating instance before calling full_clean here

vendor = Vendors.objects.create(**validated_data)
vendor.full_clean()

The first line creates the object in the database (with an empty string). The second line performs cleaning but does not save again in the database. You have to perform cleaning before saving.

vendor = Vendors(**validated_data)
vendor.full_clean()
vendor.save()
Sign up to request clarification or add additional context in comments.

4 Comments

this get the same result { "nda": [ "Date has wrong format. Use one of these formats instead: YYYY-MM-DD." ] }
And also why clean() method not run just after serializer.is_valid() method perform
@Jekson You are really confused about how form, model and serializer validation works. I would suggest to read documentation here and here.
thank for links, this is very useful information. But right now, can you tell me why your code you wrote in your answer doesn't work for me? I replaced my code with yours, but the result didn't change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.