Django: Catching Integrity Error and showing a customized message using template

前端 未结 6 2130
梦谈多话
梦谈多话 2020-12-13 03:24

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?

6条回答
  •  渐次进展
    2020-12-13 04:02

    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 }}

提交回复
热议问题