Django Rest Framework - Give Serializer of default

2019-08-19 05:41发布

问题:

I am currently making a REST API that people can register themselves via. And I am just about to write the validations for how long/complex passwords should be etc. when it occurred to me there maybe is a way to mimic the default constraints that the model have set already? Is there?

My code for serializer.py looks like the following:

from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework.reverse import reverse

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    links = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'email', 'password', 'groups', 'user_permissions', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'links')

    def get_links(self, obj):
        request = self.context['request']
        username = obj.get_username()
        return{
            'self': reverse('user-detail', kwargs={User.USERNAME_FIELD: username}, request=request)
        }

    def validate(self, attrs):
        #...

Thanks

回答1:

You can enable Django password validation with AUTH_PASSWORD_VALIDATORS setting. But

Validators aren’t applied at the model level, for example in User.objects.create_user() and create_superuser().

So you need to add validation to the serializer:

from django.contrib.auth.password_validation import validate_password

def validate_password(self, value):
    user = self.context['request'].user
    validate_password(password=value, user=user)