Hi, @pymike00. Thank you very much for your courses on Udemy. It is really nice and productivity.
I suggest for you using another way to using try/except in your courses. I think start coding in the properly way is better for any students.
This one:
def product_detail(request, pk):
try:
product = Product.objects.get(pk=pk)
data = {"product": {
"name": product.name,
"manufacturer": product.manufacturer.name,
"description": product.description,
"photo": product.photo.url,
"price": product.price,
"shipping_cost": product.shipping_cost,
"quantity": product.quantity,
}}
response = JsonResponse(data)
except Product.DoesNotExist:
response = JsonResponse({
"error": {
"code": 404,
"message": "product not found!"
}},
status=404)
return response
Should be written as:
def product_detail(request, pk):
try:
product = Product.objects.get(pk=pk)
except Product.DoesNotExist: # we should handle any exceptions as soon as possible
response = JsonResponse({
"error": {
"code": 404,
"message": "product not found!"
}},
status=404)
else:
data = {"product": {
"name": product.name,
"manufacturer": product.manufacturer.name,
"description": product.description,
"photo": product.photo.url,
"price": product.price,
"shipping_cost": product.shipping_cost,
"quantity": product.quantity,
}}
response = JsonResponse(data)
return response