python - DRF - 发布JSON对象时日期值的KeyError

时间:2018-04-25 03:54:46

标签: python django django-rest-framework

我的问题类似于已发布的here,但存在一些差异。我正在使用Django' AbstractUser类在Python 3.6上编写Django(版本2)Rest Framework(版本3.7)的用户创建Web界面。

我的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)

我的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

现在当我发布一个JSON字符串来创建用户时,我总是有以下错误:

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'

我检查了不同的来源并尝试了不同的方法来反序列化并保存JSON对象,但没有运气。有人能告诉我我的问题在哪里吗?

P.S:根据要求,我已添加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='{}')

和样本数据:

  {
    "username": "12345678000",
    "password": "thisisatest",
    "last_login": null,
    "is_superuser": false,
    "email" : "h.g@gmail.com",
    "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/APpgCI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60/RMa105omO8A88NrlOLkx2lqAAAAAAA6aejev0x3lzStmU51XiJkFyAAAAAAAAAAAAAAAAAAACl2jRjUz6oyw2vT7VM+ivAAAAAAATdk/jz4AFsAAAAAAAAAAAAAAAAAAACBtb8KPKrAAAAAH/2Q==",
    "official_docs": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxAPBhAREQ8QDQ8PDxIWEBAWFRANDxAQFRUWFhURExUYHSggGBolGxUTITEhJSkrLi4uFx8zODMsNygtLisBCgoKBQUFDgUFDisZExkrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIAOEA4QMBIgACEQEDEQH/xAAbAAEAAgMBAQAAAAAAAAAAAAAABAUBAgMGB//EADIQAQABAwEHAQYEBwAAAAAAAAABAgMRBAUSITFBUXFhIjKRobHBM4HR8RMjQmJyguH/xAAVAQEBAAAAAAAAAAAAAAAAAAAAAf/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/APpgCIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADDIAAAAAAAAAAAAAAAAAAAAAAANrduaq8RGZkGqVY0FdXON2PXn8E/SaOKIzPGrv0jwlAhW9nURHHNU/B3p0tER7sOwDjVpaJj3YcbmzqJjhmJTAFPf0FdPGPaj5/BEejRtVo4rjPKrv38gpRtdtzTXiYxLUAAAAAAAAAAAAAAAAAACIzOO670emi3b/unnP2Q9l2M1zVPKOXlaAAAAAAAAA4azTxct+scpUlVMxVieEw9ErNq2MVRVHXn57grwAAAAAAAAAAAAAAAAbW4zciO8x9QXekt7unpj0diOQAAAAAAAAA5aq3vWJj04eXUB5yRtejF2fMtQAAAAAAAAAAAAAAG9n8an/KPq0InE57A9GMUTmiJ7wyAAAAAAAAADFdWKJntAKDUT/Oq8tGa5zXPlgAAAAAAAAAAAAAAAAFxs29vWMdafolqLR39y9E9J4T4XkTmMxxiQZAAAAAAAARNpXd2xjrV9OqVM4jM8IhSay/v3pnpHLwDgAAAAAAAAAAAAAAAAAAnaDWbvs1cuk9kEB6OJ4Cp0F65E4iJqp7f9W0cgAAAAAVevuXJ4TE00+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"]
}

1 个答案:

答案 0 :(得分:5)

date_of_birth已从验证数据中删除,因为您已向此字段添加了auto_now_add=True。这告诉序列化器将自动设置值,并且不需要从用户接收它。 要修复它,只需删除模型中的auto_now_add=True

date_of_birth = models.DateField(blank=True)

并运行makemigrationsmigrate

同样正如rtindru在评论中所说,在序列化程序的创建方法中你不需要hashed_password = make_password(validated_data['password'])set_password会为您进行散列,只需使用:

user.set_password(validated_data['password')