I am writing a code that generates a coupon(reward) when a customer places an order worth a certain amount of money but I keep getting the above error message. The order is successfully placed but the coupon is not generated.
This is what I have in my views.py file
@api_view(['POST'])
def coupon_code_generator(request):
coupon_amount = request.data.get('coupon_amount')
print("The coupon amount is ", coupon_amount)
serializer = CouponSerializer(data=request.data)
if serializer.is_valid():
serializer.save(user=request.user)
qset = Coupon.objects.filter(user=request.user)
customer_name = qset[0].user.first_name
phone_number = qset[0].coupon_order.phone_number
coupon_code = qset[0].coupon_code
if(phone_number.startswith("+254")):
pn = phone_number
elif(phone_number.startswith('0')):
pn = re.sub("0","+254",phone_number,1)
elif (phone_number.startswith('7') or phone_number.startswith('1')):
pn = "+254"+phone_number
elif(phone_number.startswith('254')):
pn = "+"+phone_number
sms.send(f'Dear {customer_name},as a token of our appreciation, we are thrilled to present you with an exclusive coupon code to use on your next purchase. The code is {coupon_code} and is worth {coupon_amount}',[f'{pn}'],callback=coupon_code_generator)
return Response(serializer.data)
else:
return Response('Coupon not generated')
My models.py file:
class Coupon(models.Model):
coupon_code = models.CharField(default=coupon_generator,primary_key=True,max_length=100)
coupon_amount = models.DecimalField(max_digits=8, decimal_places=2)
coupon_order = models.ForeignKey(Order,related_name='coupon_order',on_delete=models.CASCADE)
user = models.ForeignKey(UserModel,related_name='user', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created_at',)
def __str__(self):
return f"{self.coupon_order.email}({'%s' % self.coupon_order.id}) - {'%s' % self.coupon_code}"
This is my serializers.py file:
class CouponSerializer(serializers.ModelSerializer):
coupon_order = serializers.PrimaryKeyRelatedField(queryset = Order.objects.all())
user = serializers.ReadOnlyField(source='user.email')
class Meta:
model = Coupon
fields=['coupon_code','coupon_amount','user','coupon_order','created_at']
The issue was with the request data that was being passed when performing the post action on my end point. On my view function, I added an if else statement when checking if the serializer is valid.
By including the serializers.errors, I was able to notice that my request data was passing a different datatype to the one that is expected. So I was then able to pass the required datatype and it worked.