I'm trying to create an Order in Django with an optional promo_code, but I'm getting a validation error:
{"promo_code": {"code": ["This field may not be blank." ] }}
Here are my models:
class PromoCode(models.Model): code = models.CharField(max_length=255, unique=True, db_index=True)class Order(models.Model): promo_code = models.ForeignKey( PromoCode, on_delete=models.SET_NULL, null=True, blank=True )
In my OrderSerializer, I define promo_code to allow null and set required=False:
from rest_framework import serializersclass PromoCodeSerializer(serializers.ModelSerializer): class Meta: model = PromoCode fields = ['code']class OrderSerializer(serializers.ModelSerializer): promo_code = PromoCodeSerializer(allow_null=True, required=False) class Meta: model = Order fields = ['promo_code']
test_payload = {"items": [{"id": "bb6ccdd4-3218-4794-a16a-9327cdfec56f"}],"order_date": "2024-11-15","promo_code": {"code": "" },"shipping_info": {"shipping_address": "pursitie 7 F" },"first_name": "Ebenezer","last_name": "Ofori-Mensah","email": "oforimensahebenezer07@gmail.com" }
The issue is that when trying to create an order without providing a promo_code (like test_payload), I still get the validation error saying "This field may not be blank." for promo_code. I expected promo_code to be optional.