How to avoid code duplication in Django Forms and

2019-05-02 17:23发布

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?

1条回答
等我变得足够好
2楼-- · 2019-05-02 18:07

I typically do this in my serializer:

def validate(self, attrs):
    # custom serializer validation

    self.myform = self.myform_class(
        data=attrs
    }

    if not self.myform.is_valid():
        raise serializers.ValidationError()
    return attrs

This way I can reuse form validation and add custom serializer validation at the same time + use both of builtin validators.

Let me know if this helps and if not maybe you can throw some code snippets, so we can figure out your exact case.

查看更多
登录 后发表回答