Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

419
Visualizações
Is there a way to allow blank data for Django restframework

I have a products model that I want to have optional fields that are not required by the user whenever i try to input empty data it throws an error 400 back to the user meaning the serialized data is not valid

views.py

def products(request):
    if request.method == 'GET':
        products = Product.objects.filter(user=request.user)
        serializer = ProductSerializer(products, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ProductSerializer(data=request.data)
        serializer.initial_data['user'] = request.user.pk
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializer.py

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'

models.py

class Product(models.Model):
    name = models.CharField(max_length=50)
    description = models.TextField(blank=True)
    price = models.FloatField()
    quantity = models.IntegerField(blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    shop = models.ForeignKey(Shop, on_delete=models.DO_NOTHING)
    discount = models.FloatField(default=0)
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The way DRF understands what field is required is by looking at your model field's option called null (docs).

If null=True, DRF will handle this field as not required

If you do not want to set this option in your model's class, you can make it work in serializer class via required option, e.g.

class ProductSerializer(serializers.ModelSerializer):
    name = serializer.CharField(required=False)

    class Meta:
        model = Product
        fields = '__all__'
over 4 years ago · Santiago Trujillo Relatório

0

You have to specifying fields explicitly and add required=false like this :

class ProductSerializer(serializers.ModelSerializer):
    # We make the description field empty
    description = serializers.CharField(max_length=200, required=False)
    class Meta:
        model = Product
        fields = ['name', 'description', 'user' , 'shop' ...] # Each field you want in the response.
        # Or you can use extra_kwargs since DRF 3.12.x
        extra_kwargs = {"description": {"required": False, "allow_null": True}}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda