Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!