1👍
You may have imported it incorrectly
To catch a duplicate of a unique model being created use:
from django.db import IntegrityError
def add_person(request, name):
try:
person = UniquePerson.objects.create(name = name)
return HttpResponse("...")
except IntegrityError as e:
return HttpResponse(f"Error: {e.__cause__} or {e.message}")
👤liam
0👍
Although you might do this with try/except, you may aswell do it with a simple if else clause:
if UniquePerson.objects.filter(name=name).first() is None:
person = UniquePerson.objects.create(name=name)
return HttpResponse(f"New person with name: {name} added")
else:
return HttpResponse(f"Error: person with name: {name} already registered in DB")
- [Answered ]-Django count annotation field
- [Answered ]-Missing datepicker in Django 1.3 admin
- [Answered ]-Django Templates Variable Resolution
Source:stackexchange.com