In my recent project there was a lot of data business logic, so I had to organize this code somehow. In this article I'll describe a few hints on how to it.
Simple business logic functions should in models or managers. When there's a lot of them, the can be split in mixins.
# logic.py
class EventLogic(object):
def start(self):
if self.condition():
# ...
# models.py
class Event(models.Model, EventLogic):
name = models.CharField()
# ...
For business logic errors you should declare custom exception classes. It's not fun to understand what this specific IntegrityError means.
When all logic is in model and can throw, say, BusinessLogicException
, we can write views like this:
from django.contrib import messages
def event_action(requets, event_id, action):
# event = get_object_or_404(...)
try:
getattr(event, action)(request.user)
except BusinessLogicException, e:
messages.warning(request, e.message)
return redirect(request.POST.get('next') or event)