1

My problem is similar to what has been posted here but with some differences. I am writing a user creation web interface with Django (ver. 2) Rest Framework (ver. 3.7) on Python 3.6, using Django's AbstractUser class.

My views.py:

   def post(self, request, format=None):
        serializer = UserProfileSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

My serializers.py :

class UserProfileSerializer(serializers.ModelSerializer):

    avatar = Base64ImageField()
    official_docs = Base64ImageField()

    class Meta:
        model = UserProfile
        fields = '__all__'
        extra_kwargs = {'password': {'write_only': True},
                        }


    def create(self, validated_data):
        hashed_password = make_password(validated_data['password'])  # get the hashed password
        user = UserProfile(
            username=validated_data['username'],
            email = validated_data['email'],
            first_name= validated_data['first_name'],
            last_name= validated_data['last_name'],
            phone_number=validated_data['phone_number'],
            avatar=validated_data.pop('avatar'),
            gender=validated_data['gender'],
            city=validated_data['city'],
            description=validated_data['description'],
            date_of_birth=validated_data.pop('date_of_birth'),
            official_docs=validated_data.pop('official_docs'),
            team_name=validated_data['team_name'],
            debit_card_number=validated_data['debit_card_number'],
            favorite_music=validated_data['favorite_music'],
        )
        user.set_password(hashed_password)
        user.save()
        return user

Now when I post a JSON string to create user, I always have below error :

File "views.py" in post
  27.             serializer.save()

File ".virtualenvs/Django/lib/python3.6/site-packages/rest_framework/serializers.py" in save
  214.             self.instance = self.create(validated_data)

File "serializers.py" in create
  36.             date_of_birth=validated_data.pop('date_of_birth'),

Exception Type: KeyError at /users/
Exception Value: 'date_of_birth'

I have checked different sources and tried different methods to deserialize and save the JSON object but had no luck. Can someone show me where my problem is?

P.S: As requested, I've added my models.py :

class UserProfile(AbstractUser):

    "The Profile of a user with details are stored in this model."

    username = models.TextField(primary_key=True, max_length=11)
    first_name = models.TextField(max_length=50,blank=True,default='')
    last_name = models.TextField(max_length=100,blank=True,default='')
    phone_number = models.TextField(max_length=11,blank=True,default='')
    avatar = models.ImageField(blank=True, default='../Static/1.jpeg')
    GENDER_CHOICES = (
        ('M','Male'),
        ('F','Female'),
    )
    gender = models.CharField(max_length=1,choices=GENDER_CHOICES, default='M')
    city = models.TextField(max_length=25, blank=True, default='NY')
    description = models.TextField(max_length=2000, blank=True, default='')
    interests = models.ManyToManyField(Config_Table, blank=True, default='')
    date_of_birth = models.DateField(auto_now_add=True,blank=True)
    official_docs = models.ImageField(blank=True, default='../Static/1.jpeg')
    team_name = models.TextField(blank=True,default='')
    debit_card_number = models.IntegerField(blank=True, default=0)
    MUSIC_CHOICES = (
        ('Rock','Rock Music'),
        ('Trad','Traditional Music'),
        ('Elec','Electronic Music'),
        ('Clas','Classical Music')
    )
    favorite_music = ArrayField(models.TextField(blank=True,default=''),size=2,blank=True, default='{}')

and a sample data :

  {
    "username": "12345678000",
    "password": "thisisatest",
    "last_login": null,
    "is_superuser": false,
    "email" : "[email protected]",
    "first_name": "John",
    "last_name": "Doe",
    "phone_number": "12345678000",
    "gender": "M",
    "city": "NY",
    "description": "",
    "date_of_birth": "2010-03-28",
    "team_name": "",
    "avatar": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAPBhAREQ8QDQ8PDxIWEBAWFRANDxAQFRUWFhURExUYHSggGBolGxUTITEhJSkrLi4uFx8zODMsNygtLisBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIAOEA4QMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAABAUBAgMGB//EADIQAQABAwEHAQYEBwAAAAAAAAABAgMRBAUSITFBUXFhIjKRobHBM4HR8RMjQmJyguH/xAAVAQEBAAAAAAAAAAAAAAAAAAAAAf/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/APpgCIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADDIAAAAAA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naDWbvs1cuk9kEB6OJ4Cp0F65E4iJqp7f9W0cgAAAAAVevuXJ4TE00+nHPkDX6ze9mn3es90AAAAAAAAAAAAAAAAAAAddPYqrrxH5z0gHOiiaqsRGZWWm2dEca+Pp0S9Pp6aKeEces9ZdQYpiIjEcIZAAAAAAnkAIep0FNWZp9mfkq71mqirEx+kvQNLtqKqcTGQefEjV6Sbc96Z5T9kcAAAAAAAAAAAAAGaKZmqIjnIN9PZmu5iPznsu7FmKLeI/dppNPFu1jrPOXcAAAAAAAAAAAAGK6YmnExmJUut0v8OvvTPKfsu2l63FduYnlIPPje/ami5MT+8NAAAAAAAAAAAFlsvT/wBc/wCv6oFm3vXYiOsr6imKaIiOUA2AAAAAAAAAAAAAAABE2jp9+1mPep+cKd6NSa6zuX57TxgEcAAAAAAAAAFjsm1xmr8o+6ycdJb3dPTHpxdgAAAAAAAAAAAAAAAAEPadresZ60/RMa105omO8A88NrlOLkx2lqAAAAAAA6aejev0x3lzStmU51XiJkFyAAAAAAAAAAAAAAAAAAACl2jRjUz6oyw2vT7VM+ivAAAAAAATdk/jz4AFsAAAAAAAAAAAAAAAAAAACBtb8KPKrAAAAAH/2Q==",
    "debit_card_number": 0,
    "favorite_music": [],
    "groups": [1],
    "user_permissions": [],
    "interests": ["Ski"]
}
3
  • Can you add UserProfile model and data you tried to post? Commented Apr 25, 2018 at 3:58
  • Please add the UserProfile model to the post. Also user.set_password expects the raw password as input, not the hashed password. Please change that in your code Commented Apr 25, 2018 at 4:07
  • OK, I will change that in my code. Commented Apr 25, 2018 at 4:11

1 Answer 1

5

date_of_birth removed from validated data because you added auto_now_add=True to this field. This tells to serializer that value will be set automatically and that it's not required to receive it from user. To fix it just remove auto_now_add=True in model:

date_of_birth = models.DateField(blank=True)

and run makemigrations and migrate.

Also as rtindru said in comment you don't need hashed_password = make_password(validated_data['password']) in serializer's create methos. set_password will make hashing for you, just use:

user.set_password(validated_data['password')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.