Django-Rest password validations in two fields

Asked

Viewed 263 times

1

How to recover values from html elements in a custom validation with Django-Rest ?

How would Django-Rest the similarity with the code below ?

def clean(self):
    password1 = self.cleaned_data.get('password1')
    password2 = self.cleaned_data.get('password2')

    if password1 and password1 != password2:
        raise forms.ValidationError("Passwords don't match")

return self.cleaned_data

I’ve tried with the ( validate_password1(self, date):), but I don’t know how to recover the value of password2.

I’ve also tried with (to_internal_value), but I need the feedback as in validate_CAMPO. Example (Field:msg error)

1 answer

2

To do any other validation that requires access to multiple fields, add a method called .validate() to your subclass Serializer. This method uses a single argument, which is a dictionary of field values. It must raise a ValidationError, if necessary, or just return the validated values. For example:

from rest_framework import serializers

class EventSerializer(serializers.Serializer):
    description = serializers.CharField(max_length=100)
    start = serializers.DateTimeField()
    finish = serializers.DateTimeField()

    def validate(self, data):
        """
        Check that the start is before the stop.
        """
        if data['start'] > data['finish']:
            raise serializers.ValidationError("finish must occur after start")
        return data

Translation of the documentation excerpt.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.