Валидация в DR(Django)
Я пытаюсь создать таможенные валидации для моего serialiazer, но Django просто игнорирует их и возвращает мне ошибки по умолчанию DRF.
{'message': 'Erro ao criar camião', 'data': {'plate': [ErrorDetail(string='Это поле не может быть null.', code='null')]}}
Вот какой ответ я получил
view.py
Просмотр, позволяющий компаниям добавлять свои грузовики
class TruckView(generics.GenericAPIView):
permission_classes = [IsAuthenticated, IsCompanyAuthenticated]
queryset = Trucks.objects.all()
serializer_class = TruckSerializer
def post(self, request):
company = get_object_or_404(Company, user=request.user)
request.data['company'] = company.id
request.data['on_service'] = False
serializer = TruckSerializer(data=request.data)
if serializer.is_valid(raise_exception=False):
serializer.save()
return Response(
{
'message': "Camião criado com sucesso",
'data': serializer.data
}, status=status.HTTP_201_CREATED
)
else:
print(serializer.data)
return Response(
{
'message': "Erro ao criar camião",
'data': serializer.errors
},
status=status.HTTP_400_BAD_REQUEST
)
Serializer.py
class TruckSerializer(serializers.ModelSerializer):
company = serializers.PrimaryKeyRelatedField(queryset=Company.objects.all())
types = TypesSerializer(many=True, read_only=True)
class Meta:
model = Trucks
fields = '__all__'
def validate(self, attrs):
return super().validate(attrs)
def validate_required_field(self, value, error_message):
if not value or value in [None, "", " ", []]:
raise ValidationError(error_message)
return value
def validate_plate(self, value):
return self.validate_required_field(value, "Matricula inválida")
def validate_types(self, value):
for type_id in value:
try:
# Get the Types instance by ID
Types.objects.get(id=type_id['id'])
except Types.DoesNotExist:
# Handle the case where the type ID is not valid
raise serializers.ValidationError("Tipo de veículo inválido")
return self.validate_required_field(value, "Introduza tipo válidos para este camião")
def validate_policy_nr(self, value):
if not value.isalnum():
raise ValidationError("Numero de apólice inválido. Obrigatório ser composto apenos por números e letras")
return self.validate_required_field(value, "Numero de apolice inválida")
def validate_insurance(self, value):
return self.validate_required_field(value, "Condutor do transporte é obrigatório")
def create(self, validated_data):
if Trucks.objects.filter(plate=validated_data['plate']).exists():
raise serializers.ValidationError("Matricula ja existe")
truck = Trucks.objects.create(**validated_data)
# Handling ManyToManyField `types`
types_data = validated_data.get('types', [])
for type_id in types_data:
type_instance = Types.objects.get(id=type_id)
truck.types.add(type_instance)
return truck
def update(self, instance, validated_data):
# Handling ManyToManyField `types`
types_data = validated_data.get('types', [])
valid_types = []
for type_id in types_data:
type_instance = Types.objects.get(id=type_id)
valid_types.append(type_instance)
instance.types.set(valid_types)
instance.plate = validated_data.get('plate', instance.plate)
instance.insurance = validated_data.get('insurance', instance.insurance)
instance.policy_nr = validated_data.get('policy_nr', instance.policy_nr)
instance.save()
return super().update(instance, validated_data)
models.py
class Trucks(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
plate = models.CharField(unique=True)
insurance = models.CharField()
policy_nr = models.CharField()
on_service = models.BooleanField()
image = models.CharField()
types = models.ManyToManyField(Types)