Ticket #30627: demo30627.py

File demo30627.py, 1.7 KB (added by Antonis Christofides, 5 years ago)

A single executable Python file that illustrates the problem

Line 
1#!/usr/bin/env python
2
3import sys
4import textwrap
5
6from django.apps import apps
7from django.apps.config import AppConfig
8from django.conf import settings
9from django.db import models
10from django.http import HttpResponse
11
12APP_LABEL = "femto"
13
14settings.configure(DEBUG=True, SECRET_KEY="topsecret", ROOT_URLCONF=__name__)
15app_config = AppConfig(APP_LABEL, sys.modules["__main__"])
16apps.populate([app_config])
17
18
19class Animal(models.Model):
20 class Meta:
21 app_label = APP_LABEL
22
23
24class Mammal(Animal):
25 class Meta:
26 app_label = APP_LABEL
27
28
29class Cat(Mammal):
30 class Meta:
31 app_label = APP_LABEL
32
33
34# Try getting Animal by an erroneous non-integer pk; result should be ValueError
35try:
36 Animal.objects.get(pk="hello")
37except ValueError as e:
38 print(str(e))
39 print("Animal raised ValueError")
40
41# Same thing with Mammal
42try:
43 Mammal.objects.get(pk="hello")
44except ValueError as e:
45 print(str(e))
46 print("Mammal raised ValueError")
47
48# But Cat, instead of ValueError, raises something else
49try:
50 Cat.objects.get(pk="hello")
51except ValueError:
52 print("Cat raised ValueError")
53except Exception as e:
54 print()
55 print(str(e))
56 print(
57 textwrap.dedent(
58 """\
59 Oops! Cat raised something else than ValueError. In this example it's
60 probably ImproperlyConfigured because DATABASES is missing, but if this had
61 been properly configured, it would have been DataError, because it would
62 have created and run SQL that contains 'hello' as an integer. In contrast,
63 Animal and Mammal caught the error earlier. The most important thing is that
64 in all three cases there should have been the same exception.
65 """
66 )
67 )
Back to Top