zymud zymud - 1 year ago 158
Python Question

django rest framework serializers and django forms

Question: How to write DRY code for field validation in both form and serializer?

I have simple django app with model form, which validates

field for

def clean_passengers(self):
passengers = self.cleaned_data['passengers']
if passengers > self.flight.available_seats:
raise forms.ValidationError(
_(u'''Passengers count can`t be greater then seats count'''))
return passengers

And same code for validation in

def validate_passengers(self, attrs, source):
passengers = attrs[source]
if passengers > self.flight.available_seats:
raise serializers.ValidationError(
_(u'''Passengers count can`t be greater then seats count'''))
return attrs

This isn`t DRY and I have write same logic twice. How I can avoid this? Maybe I can inherit serializer from form or something like this.

Answer Source

You can use your serializer to deserialize and validate the data inside the is_valid method of your form.

class MyModelForm(ModelForm):
    def is_valid(self):
        # Call super's is_valid to populate cleaned_data and do basic field validation
        valid = super(MyModelForm, self).is_valid()
        if not valid:
            return False

        serializer = MyModelSerializer(data=self.cleaned_data)
        return serializer.is_valid()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download