Customize field validation and validation error message in serializer

4,031 views
Skip to first unread message

Alexander Lamas

unread,
Feb 25, 2020, 3:37:04 AM2/25/20
to Django REST framework
Hi everyone,

I'm trying to customize the a field validation + it's validation error message, as I have the following code:

VIEW:
class MyClassViewSet(viewsets.ModelViewSet):
    serializer_class = MySerializer
    queryset = mymodel.objects.all()
  
    def perform_create(self, serializer): 
        serializer.save()
 
    @method_decorator(csrf_protect)
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True) 
        self.perform_create(serializer)
 
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


SERIALIZER:
class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = mymodel
        fields = ['id', 'name', 'email', 'note', 'isdisabled']
 
    def __init__(self, *args, **kwargs):
        super(MySerializer, self).__init__(*args, **kwargs)
 
        validators = self.fields['email'].validators
        for validator in validators:
            if isinstance(validator, EmailValidator):
                validator.message = _("msgInvalidEmail")
 

MODEL:
class mymodel(models.Model):
    name = models.CharField(max_length=100, null=False, default=None, db_column='name')
    email = models.EmailField(max_length=254, unique=False, blank=True, null=True, db_column='email')
    note = models.CharField(max_length=500, null=True, blank=True, default=None, db_column='note')
    licensekey = models.CharField(max_length=100, null=True, db_column='licensekey')
    isdisabled = models.BooleanField(null=False, default=False, db_column='isdisabled')

Problem 1:
If I run the code like this, I get a generic error message like this, "This field may not be blank.", when I don't enter name for example.
I don't know which field the message is talking about.

If I add a validation into my serializer as follow:
def validate_name(self, value):
    if not value:
        raise serializers.ValidationError(_("msgInvalidName"))
 
def validate_licensekey(self, value):
    if not value:
        raise serializers.ValidationError(_("msgInvalidLicenseKey"))

The validation method don't get triggered.
Only if change my model adding "blank=True" for these fields in my model.

Problem 2:
If I add the field validation in my serializer and change the mode adding "blank=True" I start getting some weird behaviour when running my unit tests.

Problem 3: 
How can I check if the serializer error message already have an error message and add the "Carriage return + Line feed" to push the next validation error message to the next line?

Is there a better way to customize those validation error messages without changing the model attributes?
What would a good practice in this case?

Any help would be greatly appreciated.

Thank you!

Regards,
Alex






Alexander Lamas

unread,
Feb 26, 2020, 3:56:39 AM2/26/20
to Django REST framework
I have found a way to customize this message.

The serializer goes like this.

name = serializers.CharField(error_messages={'blank': 'My customized message for name.'})
email = serializers.CharField(error_messages={'blank': 'My customized message for email.'})


Now the only problem is, when you have both validations being triggered, the messages are just concatenated, and, now showing in separated lines.

Any clues on how to separate the messages?
Also, the messages comes like this {name: "My customized message."}
How can I show the message only and not in the JSON format?

Thank you!

Regards,
Alex
Reply all
Reply to author
Forward
0 new messages