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

前端 未结 6 2120
梦谈多话
梦谈多话 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:08

    If you're using class-based views with the CreateView mixin, you'll want to try the call to the superclass's form_valid, for example:

    from django.db import IntegrityError
    ...
    class KumquatCreateView(CreateView):
        model = Kumquat
        form_class = forms.KumquatForm
        ...
        def form_valid(self, form):
            ...
            try:
                return super(KumquatCreateView, self).form_valid(form)
            except IntegrityError:
                return HttpResponse("ERROR: Kumquat already exists!")
    

    You can use a template, render_to_response etc. to make the output nicer, of course.

提交回复
热议问题