I want to create a password on server side and send it back to the user. Below is the code I have written:
class ASCreateSerializer(serializers.Serializer):
name = serializers.CharField(write_only = True)
password = serializers.SerializerMethodField()
def get_password(self, obj):
from django.utils.crypto import get_random_string
password = get_random_string(length=16)
return password
def create(self, validated_data):
name = validated_data['name']
as = AS.objects.get_or_create(name = name,
password = validated_data['password']
)
I am getting a key error for 'password'. How can I access the value of a SerializerMethodField in create()?
SerializerMethodField (Doc) is a read-only field. This field is used when you want to compute the field for a given object and thus would not be necessary if you are receiving the input (write case). So, in you case you can generate password inside the create method and have only name in the serializer.
You can access the get_password() method by calling self.get_password() as @Andrey Shipilov mentioned. But remove the unnecessary second argument obj from definition of get_password().
If what you require is to save a random password to database and return it in response, consider doing something like:
def create_password():
from django.utils.crypto import get_random_string
password = get_random_string(length=16)
return password
class ASCreateSerializer(serializers.Serializer):
name = serializers.CharField(write_only = True)
password = serializers.CharField()
def create(self, validated_data):
name = validated_data['name']
as = AS.objects.get_or_create(
name = name,
password = create_password()
)