Returning a 404 error if the value is not in the model data

From TRCCompSci - AQA Computer Science
Revision as of 15:30, 18 March 2020 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

If you have completed the tutorial above (passing an integer via the URL), you will have a view which filters a model by the variable passed in the URL.

You should have something like this:

def showproduct(request, prodID):
    product_info = {
        'products' : Product.objects.filter(pk = prodID),
        'reviews' : Review.objects.filter(product = prodID)
    }
    return render(request, 'MyApp/showproduct.html', product_info)

'prodID' is passed into the procedure by the arguments, and then used to filter the product model by the primary key and then filter the review model by the product field.

To generate a 404 we need to import the following:

from django.http import Http404

Now we can use some exception handling to catch when a product doesn't exist:

def showproduct(request, prodID):
    try:
        product_info = {
            'products' : Product.objects.filter(pk = prodID),
            'reviews' : Review.objects.filter(product = prodID)
        }
    except Product.DoesNotExist:
        raise Http404("Product does not exist")
    return render(request, 'MyApp/showproduct.html', product_info)