DEV Community

Gahyun Son
Gahyun Son

Posted on

extra_kwargs arguments

I want to set up minimum length to password value. I looked for this argument but just got confused. Here is my steps to understand.

Where is the code defined the password?

I didn't define the password in the User model. I set up on serializer.

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ['name', 'email', 'password']
        extra_kwargs = {'password': {'write_only': True}}
Enter fullscreen mode Exit fullscreen mode

If I want to set the password minimum length,

I think extra_kwargs is also a kind of field. And you can see the documentation.

|There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the extra_kwargs option.

It means extra_kwargs is a option to set arguments on fields.
So we need to see how to set arguments on fields.

Serializer fields

So we are here. As you can see here documentation,

There are common arguments - Core arguments.
And we can see arguments each field types.

I want to set minimum length of password, it belongs to Charfield. Let's go to the Charfield list.

Signature: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)

CharField

Now I find min_length argument! I'm going to set this on my code!

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = ['name', 'email', 'password']
        extra_kwargs = {'password': {'write_only': True, 'min_length': 5}}
Enter fullscreen mode Exit fullscreen mode

It's hard to comprehend the documents right away. But we just need time, we can solve it!
Now I'm happy!

Top comments (0)