Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda