Skip to content

Commit c0ce540

Browse files
Fix review creation to properly handle unauthorized product reviews
1 parent 3952e12 commit c0ce540

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

shop/models.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,8 +156,13 @@ class Meta:
156156

157157
def save(self, *args, **kwargs):
158158
from django.core.exceptions import ValidationError
159-
if not self.product.order_items.filter(order__user=self.user).exists():
159+
160+
# Allow skipping validation when saving from view (where validation already happened)
161+
skip_validation = kwargs.pop('skip_validation', False)
162+
163+
if not skip_validation and not self.product.order_items.filter(order__user=self.user).exists():
160164
raise ValidationError("You can only review products you have purchased.")
165+
161166
super().save(*args, **kwargs)
162167

163168
def __str__(self):

shop/views.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,18 @@ def perform_create(self, serializer):
121121
product_slug = self.kwargs.get('product_slug')
122122
try:
123123
product = get_object_or_404(Product, slug=product_slug)
124+
125+
# Check if user has purchased this product before saving
126+
if not product.order_items.filter(order__user=self.request.user).exists():
127+
from django.core.exceptions import ValidationError
128+
raise ValidationError("You can only review products you have purchased.")
129+
124130
serializer.save(product=product)
125131
logger.info("Review created for product slug: %s by user id: %s", product_slug, self.request.user.id)
132+
except ValidationError as e:
133+
logger.error("Validation error creating review for product slug: %s: %s", product_slug, e)
134+
from rest_framework.exceptions import PermissionDenied
135+
raise PermissionDenied(detail=str(e.message))
126136
except Exception as e:
127137
logger.error("Error creating review for product slug: %s: %s", product_slug, e, exc_info=True)
128138
raise

0 commit comments

Comments
 (0)