Graciously handle crash while saving model via Django Admin - django

Sometimes it is not possible to know beforehand and graciously reject model save inside a validator which shows nice error message in Django Admin.
If a specific crash happens during the save operation (e.g. data integrity error) and we still want to catch it and show a nice error (similar to validation errors), there's no obvious way to do this that I could find.
I tried overriding the save_model method on Django Admin, but this is a horrible thing to do according to the docs:
When overriding ModelAdmin.save_model() and ModelAdmin.delete_model(), your code must save/delete the object. They aren’t meant for veto purposes, rather they allow you to perform extra operations.
What's the correct way to catch specific exceptions and display nice error message then?
UPDATE:
Example: integrity error when using optimistic locking.
More concrete example: ConcurrentTransition error raised by django_fsm when the object's state has been changed in DB since the object was loaded by Admin (this could be considered a light version of optimistic locking).

I found an elegant way to solve this without hacking the save_model method which is not intended for veto purposes.
Instead, it's enough to just override change_view and/or add_view and generate an error message if they crash.
Example:
from django.contrib import messages
from django.http import HttpResponseRedirect
def change_view(self, request, object_id, form_url='', extra_context=None):
try:
return super(MyAdmin, self).change_view(request, object_id, form_url, extra_context)
except MyException as err:
messages.error(request, err)
return HttpResponseRedirect(request.path)
edit: This more generic handler catches errors from Admin's AddForm as well:
from django.contrib import messages
from django.http import HttpResponseRedirect
def changeform_view(self, request, *args, **kwargs):
try:
return super().changeform_view(request, *args, **kwargs)
except IOError as err:
self.message_user(request, str(err), level=messages.ERROR)
return HttpResponseRedirect(request.path)

Related

Django class-based view to return HttpResponse such as HttpResponseBadRequest

I have a custom Django view class that inherits from the generic DetailView.
The generic DetailView class sequentially calls its methods get_queryset, get_object, and others to generate an object to pass for a Django template.
Moreover, the generic DetailView class raises Http404 exception within these methods to deal with erroneous situations #.
except queryset.model.DoesNotExist:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
What I am trying to do is simple: I want to return other HTTP status codes to the client if an error is found within these methods. However, because Http404 is the only Django HttpResponse that has a form of exception, it seems like this cannot be achieved easily.
Because HttpResponse is not an exception, I have to return it instead of raising it. Therefore, the customized method becomes the following form.
def get_object(self, queryset=None):
...
try:
# Get the single item from the filtered queryset
obj = queryset.get()
except queryset.model.DoesNotExist:
return HttpResponseBadRequest("Bad request.")
However, above code does not send HttpResponseBadRequest to the client. Instead, it returns HttpResponseBadRequest as an object for a Django template. The client gets 200 status code with an invalid object for the template.
The only possible solution to think is writing some object-checking code within the Django template. However, I wonder if there is any better way to deal with this problem.
Since Django 3.2 we now have an exception BadRequest [Django docs] which will be turned into a HttpResponseBadRequest internally when caught, so you can try catching Http404 and raising BadRequest instead:
from django.core.exceptions import BadRequest
class MyView(SomeGenericView):
...
def get_object(self, queryset=None):
try:
return super().get_object(queryset=queryset)
except Http404 as e:
# raise BadRequest("Bad request.") from e
raise BadRequest("Bad request.")
For some previous version we can try to catch the exception at the dispatch method and return the appropriate response there:
class MyView(SomeGenericView):
...
def dispatch(self, request, *args, **kwargs):
try:
return super().dispatch(request, *args, **kwargs)
except Http404:
return HttpResponseBadRequest("Bad request.")

Catch exception on save in Django admin?

I have a pre_save signal handler on a bunch of models, which write to a different database. If something goes wrong, I'd like to abort the whole save, or failing that give a message to the user.
Based on Display custom message from signal in the admin, I wrote a mixin with methods like:
class SafeSaveMixin(object):
def save_model(self, request, *args, **kwargs):
try:
return super(SafeSaveMixin, self).save_model(request, *args, **kwargs)
except Exception as e:
self.message_user(request, e, messages.ERROR)
This allows me to throw an Exception from the pre_save handler and show the message to the user. The problem is, even though this winds up skipping the actual Model.save(), the admin console doesn't see anything, so it still reports the object as successfully saved.
If I changed the pre_save handler to a post_save handler, that would allow the base Model.save() to occur and at least Django would report the correct state of things, but the information I need in the other database is based on the previous state of the object, so I need to get to it before the save.
I've also considered stuffing the error message into the object itself in the pre_save and pulling it out in the mixin's save_model() -- but this gets more complicated in the other ModelAdmin save methods like save_formset().
Is there any good way to do this?
I've come up with this, which gets mixed in to the ModelAdmin class:
class InternalModelAdminMixin:
"""Mixin to catch all errors in the Django Admin and map them to user-visible errors."""
def change_view(self, request, object_id, form_url='', extra_context=None):
try:
return super().change_view(request, object_id, form_url, extra_context)
except Exception as e:
self.message_user(request, 'Error changing model: %s' % e.msg, level=logging.ERROR)
# This logic was cribbed from the `change_view()` handling here:
# django/contrib/admin/options.py:response_post_save_add()
# There might be a simpler way to do this, but it seems to do the job.
return HttpResponseRedirect(request.path)
This doesn't interfere with the actual model save process, and simply prevents the 500 error redirect. (Note this will disable the debug stacktrace handling. You could add some conditional handling to add that back in).
Catching this kind of errors should not be desirable. This could mean you expose delicate information to your users, e.g. about database (if there is an IntegrityError). As this bypasses the normal error handling, you might also miss messages that inform you about errors.
If there's some check required for wrong/incomplete data a user has entered, then the way to go is to do this in def clean(self)
def clean(self):
cleaned_data = super(ContactForm, self).clean()
field_value = cleaned_data.get('field_name')
if not field_value:
raise ValidationError('No value for field_name')
class YourModel(models.Model):
def clean(self):
# do some validation
# or raise ValidationError(...)
pass
def save(self, *args, **kwargs):
self.full_clean()
super(YourModel, self).save(*args, **kwargs)
It usually works, and you should not do any validation in other place.
But if you use RelatedField with InlineAdmin, and validation by related instance.
Sometimes it will be wrong, Django won't render your Exceptions.
Like this question: how to display models.full_clean() ValidationError in django admin?
It confuse me about two month. And make me saw lots sources code.
Just now,I fixed it in my project(maybe...)
Hope no bug...

How to return an error message from the Model?

In suppliment to this question, if business logic should be in the model, how do I return an error message from the model?
def save(self, *args, **kwargs):
if <some condition>:
#return some error message to the view or template
Pastylegs is correct, but you shouldn't be doing that sort of logic in the save method. Django has a built-in system for validating model instances before saving - you should use this, and raise ValidationError where necessary.
Raising an exception is the way to report a program logic error (an error in 'business logic'), which is what you are talking about. You can just raise an Exception, as pastylegs proposes (be aware that SomeException is just a placeholder):
from django.core.exceptions import SomeException
def save(self, *args, **kwargs):
if <some condition>:
raise SomeException('your message here')
You can find the available exceptions fpr django here: https://docs.djangoproject.com/en/1.3/ref/exceptions/ ,plus you can also use the standard python exceptions, for which you can find documentation here: http://docs.python.org/library/exceptions.html
I would recommend you to find an Exception that describes your problem, or you will be pretty confused if that error shows up in a few weeks, when you cannot remember what exactly you have been doing now.

Tastypie-django custom error handling

I would like to return some JSON responses back instead of just returning a header with an error code. Is there a way in tastypie to handle errors like that?
Figured it out eventually. Here's a good resource to look at, if anyone else needs it. http://gist.github.com/1116962
class YourResource(ModelResource):
def wrap_view(self, view):
"""
Wraps views to return custom error codes instead of generic 500's
"""
#csrf_exempt
def wrapper(request, *args, **kwargs):
try:
callback = getattr(self, view)
response = callback(request, *args, **kwargs)
if request.is_ajax():
patch_cache_control(response, no_cache=True)
# response is a HttpResponse object, so follow Django's instructions
# to change it to your needs before you return it.
# https://docs.djangoproject.com/en/dev/ref/request-response/
return response
except (BadRequest, ApiFieldError), e:
return HttpBadRequest({'code': 666, 'message':e.args[0]})
except ValidationError, e:
# Or do some JSON wrapping around the standard 500
return HttpBadRequest({'code': 777, 'message':', '.join(e.messages)})
except Exception, e:
# Rather than re-raising, we're going to things similar to
# what Django does. The difference is returning a serialized
# error message.
return self._handle_500(request, e)
return wrapper
You could overwrite tastypie's Resource method _handle_500(). The fact that it starts with an underscore indeed indicates that this is a "private" method and shouldn't be overwritten, but I find it a cleaner way than having to overwrite wrap_view() and replicate a lot of logic.
This is the way I use it:
from tastypie import http
from tastypie.resources import ModelResource
from tastypie.exceptions import TastypieError
class MyResource(ModelResource):
class Meta:
queryset = MyModel.objects.all()
fields = ('my', 'fields')
def _handle_500(self, request, exception):
if isinstance(exception, TastypieError):
data = {
'error_message': getattr(
settings,
'TASTYPIE_CANNED_ERROR',
'Sorry, this request could not be processed.'
),
}
return self.error_response(
request,
data,
response_class=http.HttpApplicationError
)
else:
return super(MyResource, self)._handle_500(request, exception)
In this case I catch all Tastypie errors by checking if exception is an instance of TastypieError and return a JSON reponse with the message "Sorry, this request could not be processed.". If it's a different exception, I call the parent _handle_500 using super(), which will create a django error page in development mode or send_admins() in production mode.
If you want to have a specific JSON response for a specific exception, just do the isinstance() check on a specific exception. Here are all the Tastypie exceptions:
https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py
Actually I think there should be a better/cleaner way to do this in Tastypie, so I opened a ticket on their github.

Creating custom Exceptions that Django reacts to

For my site I created an abstract Model which implements model-level read permissions. That part of the system is completed and works correctly. One of the methods the permissioned model exposes is is_safe(user) which can manually test if a user is allowed to view that model or not.
What I would like to do is add a method to the effect of continue_if_safe which can be called on any model instance, and instead of returning a boolean value like is_safe it would first test if the model can be viewed or not, then in the case of False, it would redirect the user, either to the login page if they aren't already logged in or return a 403 error if they are logged in.
Ideal usage:
model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
# ... remainder of code to be run if it's safe down here ...
I peeked at how the get_object_or_404 works, and it throws an Http404 error which seems to make sense. However, the problem is that there don't seem to be equivalent redirect or 403 errors. What's the best way to go about this?
(non-working) continue_if_safe method:
def continue_if_safe(self, user):
if not self.is_safe(user):
if user.is_authenticated():
raise HttpResponseForbidden()
else:
raise HttpResponseRedirect('/account/')
return
Edit -- The Solution
The code for the final solution, in case other "stackers" need some help with this:
In the Abstract Model:
def continue_if_safe(self, user):
if not self.is_safe(user):
raise PermissionDenied()
return
Views are caught by the middleware:
class PermissionDeniedToLoginMiddleware(object):
def process_exception(self, request, exception):
if type(exception) == PermissionDenied:
if not request.user.is_authenticated():
return HttpResponseRedirect('/account/?next=' + request.path)
return None
Usage in the view (very short and sweet):
model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
For the forbidden (403) error, you could raise a PermissionDenied exception (from django.core.exceptions).
For the redirecting behaviour, there's no built-in way to deal with it the way you describe in your question. You could write a custom middleware that will catch your exception and redirect in process_exception.
I've made a little middleware that return whatever your Exception class's render method returns. Now you can throw custom exception's (with render methods) in any of your views.
class ProductNotFound(Exception):
def render(self, request):
return HttpResponse("You could ofcourse use render_to_response or any response object")
pip install -e git+http://github.com/jonasgeiregat/django-excepted.git#egg=django_excepted
And add django_excepted.middleware.ExceptionHandlingMiddleware to your MIDDLEWARE_CLASSES.
Django annoying has a solution for this:
from annoying.exceptions import Redirect
...
raise Redirect('/') # or a url name, etc
You want to use decorators for this. Look up login_required for an example. Basically the decorator will allow you check check the safety and then return HttpResponseRedirect() if its not safe.
Your code will end up looking something like this:
#safety_check:
def some_view(request):
#Do Stuff