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...
Related
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)
I have a unique constraint on a database field. When a duplicate is submitted I'd like to avoid sending a 500 response. How can I catch this error in DRF and return a 4XX response instead?
I knew I needed to put a try/except block around something, but I didn't know what. I looked at the DRF code, and I saw that generics.ListCreateAPIView has a method called create. I wrote a new function inside my class called the parent create which has the same signature as the one I inherited, which called create, and I put the try/except around this function.
In the end it looks like this:
class MyModelList(generics.ListCreateAPIView):
def get_queryset(self):
return MyModel.objects.all()
def create(self, request, *args, **kwargs):
try:
return super(MyModelList, self).create(request, *args, **kwargs)
except IntegrityError:
raise CustomUniqueException
serializer_class = MyModelSerializer
I hope this helps someone.
If you want this only for this view override handle_exception:
class MyAPIView(APIView):
...
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate
response,or re-raising the error.
"""
...
To handle it for all views, you can define a global exception handler, see here: http://www.django-rest-framework.org/api-guide/exceptions
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.
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
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 that no matter where I save the instance this code validates that it can be saved.
At the moment I have this code in a custom save function of my model class:
def save(self):
if self.is_available(): # my custom check availability function
super(MyObj, self).save()
else:
# this is the bit I'm stuck with..
raise forms.ValidationError('Item already booked for those dates')
This works fine - the error is raised if the item is unavailable, and my item is not saved. I can capture the exception from my front end form code, but what about the Django admin site? How can I get my exception to be displayed like any other validation error in the admin site?
In django 1.2, model validation has been added.
You can now add a "clean" method to your models which raise ValidationError exceptions, and it will be called automatically when using the django admin.
The clean() method is called when using the django admin, but NOT called on save().
If you need to use the clean() method outside of the admin, you will need to explicitly call clean() yourself.
http://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#validating-objects
So your clean method could be something like this:
from django.core.exceptions import ValidationError
class MyModel(models.Model):
def is_available(self):
#do check here
return result
def clean(self):
if not self.is_available():
raise ValidationError('Item already booked for those dates')
I haven't made use of it extensively, but seems like much less code than having to create a ModelForm, and then link that form in the admin.py file for use in django admin.
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)
The best way is put the validation one field is use the ModelForm... [ forms.py]
class FormProduct(forms.ModelForm):
class Meta:
model = Product
def clean_photo(self):
if self.cleaned_data["photo"] is None:
raise forms.ValidationError(u"You need set some imagem.")
And set the FORM that you create in respective model admin [ admin.py ]
class ProductAdmin(admin.ModelAdmin):
form = FormProduct
I've also tried to solve this and there is my solution- in my case i needed to deny any changes in related_objects if the main_object is locked for editing.
1) custom Exception
class Error(Exception):
"""Base class for errors in this module."""
pass
class EditNotAllowedError(Error):
def __init__(self, msg):
Exception.__init__(self, msg)
2) metaclass with custom save method- all my related_data models will be based on this:
class RelatedModel(models.Model):
main_object = models.ForeignKey("Main")
class Meta:
abstract = True
def save(self, *args, **kwargs):
if self.main_object.is_editable():
super(RelatedModel, self).save(*args, **kwargs)
else:
raise EditNotAllowedError, "Closed for editing"
3) metaform - all my related_data admin forms will be based on this (it will ensure that admin interface will inform user without admin interface error):
from django.forms import ModelForm, ValidationError
...
class RelatedModelForm(ModelForm):
def clean(self):
cleaned_data = self.cleaned_data
if not cleaned_data.get("main_object")
raise ValidationError("Closed for editing")
super(RelatedModelForm, self).clean() # important- let admin do its work on data!
return cleaned_data
To my mind it is not so much overhead and still pretty straightforward and maintainable.
from django.db import models
from django.core.exceptions import ValidationError
class Post(models.Model):
is_cleaned = False
title = models.CharField(max_length=255)
def clean(self):
self.is_cleaned = True
if something():
raise ValidationError("my error message")
super(Post, self).clean()
def save(self, *args, **kwargs):
if not self.is_cleaned:
self.full_clean()
super(Post, self).save(*args, **kwargs)