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

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

    Simplest solution: write a middleware implementing process_exception that only catches IntegrityError and returns an HttpResponse with your rendered template, and make sure this middleware is after the default error handling middleware so it is called before (cf https://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception for more).

    Now if I was you, I wouldn't assume such a thing as "there is only one obvious case where "IntegrityError" can arise", so I strongly recommand you do log the exception (and send email alerts) in your middleware.

提交回复
热议问题