'Django does not threat exceptions
Could you please help me? Django does not threat the exceptions. I would like it returns the integrity exception block when this case occur. But nothing, it continue to the else block which raise the integrity exception. I tried with from django.db.utils import IntegrityError and from django.db import IntegrityError
datafile = csv.DictReader(datafile, delimiter=',')
roadnetwork = RoadNetwork.objects.get(id=pk)
for row in datafile:
row = {k: None if not v else v for k, v in row.items()}
try:
road_type_id = row['id']
name = row['name']
roadtype = RoadType(
road_type_id=road_type_id,
name=name,
congestion=CONGESTION_TYPES[row['congestion'].lower()],
default_speed=row.get('default_speed', None),
default_lanes=row.get('default_lanes', None),
default_param1=row.get('default_param1', None),
default_param2=row.get('default_param2', None),
default_param3=row.get('default_param3', None),
color=row.get('color', None))
except IntegrityError:
e = 'this data already exists in the database'
return render(request, template, context={'e': e})
else:
roadtype = RoadType(
road_type_id=road_type_id,
name=name,
congestion=CONGESTION_TYPES[row['congestion'].lower()],
default_speed=row.get('default_speed', None),
default_lanes=row.get('default_lanes', None),
default_param1=row.get('default_param1', None),
default_param2=row.get('default_param2', None),
default_param3=row.get('default_param3', None),
color=row.get('color', None),
network=roadnetwork)
Solution 1:[1]
You need to be committing the item to the database:
try:
roadtype = RoadType.objects.create(
...
)
except IntegrityError:
...
else:
...
Currently this will create the object, but not save it to the database, so you can't get an IntegrityError.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom Hamilton Stubber |
