In my django powered app there is only one obvious case where \"IntegrityError\" can arise.
So, how can I catch that error and display a message using templates?
I did it like this
from django.db import IntegrityError
from django.shortcuts import render
from .models import Person
from .forms import PersonForm
class PersonView(View):
def get(self, request):
pd = PersonForm()
return render(request, "app1/my_form.html", context={ 'form': pd })
def post(self, request):
pd = PersonForm(request.POST)
if pd.is_valid():
name = pd.cleaned_data['name']
age = pd.cleaned_data['age']
height = pd.cleaned_data['height']
p = Person()
p.name = name
p.age = age
p.height = height
try:
p.save()
except IntegrityError as e:
e = 'this data already exists in the database'
return render(request, "app1/my_form.html", context={ 'form': pd, 'e': e})
context = {
'person': {
'name': name,
'age': age,
'height': height,
},
'form': pd
}
else:
print("Form is invalid")
context = { 'form': pd }
return render(request, "app1/my_form.html", context=context)
in the template ,i can access the erroe as {{ e }}