I work on a Django 1.8 project that must expose both a traditional HTML front-end and a JSON API. For the API we're using Django Rest Framework. Having worked with Rails, I try to follow the "Fat Models" pattern and place as much validation as humanly possible in the model and away from the form. Sometimes, however, there is custom validation that must be done at form level.
Example: I have a Image
model that has a GenericForeignKey
field and can potentially be related to any model in the system. These images also have a profile
(e.g. 'logo', 'banner', etc). Depending on the profile, I need to do different validation. In principle I'd just create different form classes for different profiles, but it should also be possible to assign images to objects through the API. How can I avoid duplicating this custom validation both in Forms and Serializers?