【问题标题】:How I can send JSON on Django request to create a new User and Profile?如何在 Django 请求中发送 JSON 以创建新的用户和配置文件?
【发布时间】:2017-03-06 22:04:41
【问题描述】:

从 django rest 框架站点示例中,我编写了我的 UserSerializer.py,我的 ProfileSerializer 是这样的:

class ProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = Profile
        fields = ['facebook_id', 'facebook_token', 'push_device_token', 'photo', 'status', 'level']

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ('username', 'email', 'profile')

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user

我正在发送这样的 JSON 请求:

{
   "username":"admin",
   "email":"e@e.com",
   "password":12345678,
   "profile":{
      "status":1,
      "level":1,
      "facebook_id":1,
      "facebook_token":1,
      "push_device_token":1,
      "photo":"url.com"
   }
}

但我只得到错误:

尝试在序列化程序 UserSerializer 上获取字段 profile 的值时出现 AttributeError。

序列化器字段可能命名不正确,并且与 User 实例上的任何属性或键都不匹配。

原始异常文本是:“用户”对象没有属性“配置文件”。

【问题讨论】:

  • 我希望您不应该在字段列表中包含个人资料,因为它实际上不是模型上的字段。
  • 你有没有尝试打印验证数据...也放了完整的回溯
  • @DanielRoseman 在字段列表中没有个人资料,我收到以下错误:The field 'profile' was declared on serializer UserSerializer, but has not been included in the 'fields' option.
  • 请显示ProfileSerializer
  • 尝试将其从字段以及声明 profile = ProfileSerializer() 中删除。它应该可以工作,因为序列化程序中没有其他依赖 b/w 两个模型。

标签: python json django rest django-rest-framework


【解决方案1】:

我认为这可能是缺少对 User 模型的参考。假设您的 Profile 模型如下所示:

class Profile(models.Model):
    user = models.ForeignKey(User)

模型用户将具有profile_set 属性,而不是profile。要对此进行调整,请使用 related_name:

class Profile(models.Model):
    user = models.OneToOneField(User, related_name='profile')

【讨论】:

  • 实际上应该是user = models.OneToOneField(User)。在这种情况下,这个问题就不会发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-15
  • 2018-02-07
  • 2018-04-05
  • 1970-01-01
  • 2011-07-31
  • 2015-08-02
  • 2012-07-14
相关资源
最近更新 更多