Home > Software engineering >  Is there a way to allow blank data for Django restframework
Is there a way to allow blank data for Django restframework

Time:11-26

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)

CodePudding user response:

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__'

CodePudding user response:

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}}
  • Related