Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
Accessing a SerializerMethodField in create()

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()?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

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()
            )
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda