Opened 10 years ago

Closed 10 years ago

#22303 closed New feature (wontfix)

Have get_object_or_404 check catch ValueError

Reported by: eddie@… Owned by: nobody
Component: Uncategorized Version: 1.6
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

A pretty simple change, but one that I would find very helpful in production use. Basically, get_object_or_404 catches queryset.model.DoesNotExist and turns that into Http404, and I think it would be helpful if it also caught ValueError to handle the case where the passed in parameter is not valid for the field (like if it's a string and the field type is Integer, for example).

from django.shortcuts import get_object_or_404
from django.db.models.base import ModelBase
from django.contrib.contenttypes.models import ContentType

def test_get_object_or_404():
    # print "<ContentType: content type>"
    print get_object_or_404(ContentType, id='1')

    # raise Http404: No ContentType matches the given query.
    print get_object_or_404(ContentType, id='123456789')

    # raise ValueError: invalid literal for int() with base 10: '123a'
    print get_object_or_404(ContentType(), id='123a')

Change History (1)

comment:1 by Simon Charette, 10 years ago

Resolution: wontfix
Status: newclosed
Type: UncategorizedNew feature

I think cloaking ValueError at queryset creation time would cause more more harm than good.

Django already provides a way to sanitize/validate user input through forms. URL patterns can also provide an extra layer of data validation.

You should make sure your lookup values have been cleaned up before using them. The third party app django-filter does a good job at this.

Note: See TracTickets for help on using tickets.
Back to Top