Problem statement
A shop needs a product page and a small JSON API for the same products. The Product model, the URL routes and the detail template are provided, but both views in app/views.py are still stubs. Implement product_detail and product_json so a known product renders its page or its JSON, and a missing product answers 404 on both instead of crashing the server.
Sample Data
The provided Product model (app/models.py) has name (CharField), description (TextField, may be blank) and price (DecimalField, 2 decimal places). Example rows:
| id | name | description | price |
|---|---|---|---|
| 1 | Desk Lamp | Adjustable LED lamp | 39.90 |
| 2 | Coffee Mug | (blank) | 8.50 |
Requirements
Only app/views.py needs to change. The routes in app/urls.py and the template app/templates/app/product_detail.html are provided.
1. Detail view - GET /products/<id>/ (name="product-detail")
- Implement product_detail(request, pk).
- For a known id, render app/product_detail.html with the product in the template context under the key product, returning 200.
- For an id with no product (never existed, or deleted), return 404 instead of raising an unhandled error. Django has a shortcut for exactly this look-up-or-404 case.
2. JSON endpoint - GET /api/products/<id>/ (name="product-json")
- Implement product_json(request, pk).
- For a known id, return 200 with a JSON body that is exactly these fields and nothing else:
- id - integer primary key
- name - string
- description - string (an empty string when blank)
- price - string with two decimal places, e.g. "39.90"
- The Content-Type header must be application/json. Do not build the JSON string by hand; values containing quotes, backslashes or newlines must still produce valid JSON.
- For an id with no product (never existed, or deleted), return 404.
Sample Requests & Responses
GET /products/1/
200, HTML rendered from app/product_detail.html; the template context contains product (the Desk Lamp instance).
GET /products/999/
404
GET /api/products/1/
200, Content-Type: application/json
{"id": 1, "name": "Desk Lamp", "description": "Adjustable LED lamp", "price": "39.90"}
GET /api/products/2/
200, Content-Type: application/json
{"id": 2, "name": "Coffee Mug", "description": "", "price": "8.50"}
GET /api/products/999/
404
