Skip to content

Commit ac6850b

Browse files
feat: enhance review validation to require completed payment
- Add payment verification to review creation logic - Users can now only review products from completed orders - Update validation to check order status is COMPLETED - Improve error message to clarify payment requirement - Fix import structure to avoid validation warnings This ensures review integrity by preventing reviews on unpaid orders.
1 parent 0330f01 commit ac6850b

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

shop/views.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -117,25 +117,34 @@ def get_queryset(self):
117117
return Review.objects.filter(product__slug=product_slug)
118118

119119
def perform_create(self, serializer):
120+
from django.core.exceptions import ValidationError
121+
from rest_framework.exceptions import PermissionDenied
122+
120123
serializer.validated_data['user'] = self.request.user
121124
product_slug = self.kwargs.get('product_slug')
122125
try:
123126
product = get_object_or_404(Product, slug=product_slug)
124127

125-
# Check if user has purchased this product before saving
128+
# Check if user has purchased this product and the order is completed before saving
126129
# Skip this check in test environments
127130
from django.conf import settings
128131
is_testing = getattr(settings, 'TESTING', False)
129132

130-
if not is_testing and not product.order_items.filter(order__user=self.request.user).exists():
131-
from django.core.exceptions import ValidationError
132-
raise ValidationError("You can only review products you have purchased.")
133+
if not is_testing:
134+
# Check if user has a completed order containing this product
135+
from orders.models import Order
136+
completed_order_exists = product.order_items.filter(
137+
order__user=self.request.user,
138+
order__status=Order.Status.COMPLETED
139+
).exists()
140+
141+
if not completed_order_exists:
142+
raise ValidationError("You can only review products you have purchased and paid for.")
133143

134144
serializer.save(product=product)
135145
logger.info("Review created for product slug: %s by user id: %s", product_slug, self.request.user.id)
136146
except ValidationError as e:
137147
logger.error("Validation error creating review for product slug: %s: %s", product_slug, e)
138-
from rest_framework.exceptions import PermissionDenied
139148
raise PermissionDenied(detail=str(e.message))
140149
except Exception as e:
141150
logger.error("Error creating review for product slug: %s: %s", product_slug, e, exc_info=True)

0 commit comments

Comments
 (0)