Showing custom model validation exceptions in the Django admin site

后端 未结 4 1271
悲&欢浪女
悲&欢浪女 2021-02-07 00:27

I have a booking model that needs to check if the item being booked out is available. I would like to have the logic behind figuring out if the item is available centralised so

4条回答
  •  后悔当初
    2021-02-07 00:51

    Pretty old post, but I think "use custom cleaning" is still the accepted answer. But it is not satisfactory. You can do as much pre checking as you want you still may get an exception in Model.save(), and you may want to show a message to the user in a fashion consistent with a form validation error.

    The solution I found was to override ModelAdmin.changeform_view(). In this case I'm catching an integrity error generated somewhere down in the SQL driver:

    from django.contrib import messages
    from django.http import HttpResponseRedirect
    
    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        try:
            return super(MyModelAdmin, self).changeform_view(request, object_id, form_url, extra_context)
        except IntegrityError as e:
            self.message_user(request, e, level=messages.ERROR)
            return HttpResponseRedirect(form_url)
    

提交回复
热议问题