How to return an error message from the Model?

柔情痞子 提交于 2020-01-15 11:45:30

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/9531850/how-to-return-an-error-message-from-the-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!