Jekson
Jekson

Reputation: 3262

Why the django models clean() method doesnt work

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]"
        }
    ]


}

Upvotes: 0

Views: 274

Answers (1)

Nafees Anwar
Nafees Anwar

Reputation: 6608

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()

Upvotes: 1

Related Questions