ValueError:无法分配“'interests': ['Technology', 'Sports', 'Health'] “Consumer.interests”必须是“Interests”实例

Posted

技术标签:

【中文标题】ValueError:无法分配“\'interests\': [\'Technology\', \'Sports\', \'Health\'] “Consumer.interests”必须是“Interests”实例【英文标题】:ValueError: Cannot assign "'interests': ['Technology', 'Sports', 'Health'] "Consumer.interests" must be a "Interests" instanceValueError:无法分配“'interests': ['Technology', 'Sports', 'Health'] “Consumer.interests”必须是“Interests”实例 【发布时间】:2021-08-26 16:09:17 【问题描述】:

这是一个 Django + ReactJS 应用程序,其中 Django 是 API 后端,ReactJS 是前端。

在用户尝试注册帐户时在注册表单中返回错误

ValueError: Cannot assign "['Sports', 'Health']": "Consumer.interests" must be a "Interests" instance.

很遗憾,SOF 的回答没有帮助解决问题,所以我请求您的帮助。

注册 API

class RegistrationAPI(generics.GenericAPIView):
    serializer_class = RegisterSerializer

    def post(self, request, *args, **kwargs):
        print("Request: ", request.data)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        print(request.data.get('is_consumer'))

        if request.data.get('is_consumer') == 'True':
            consumer_data = request.data.get('additional')

            interest_data = consumer_data.get('interests')
            #interest_data = consumer_data.getlist('interests')
            print("the data is ", interest_data)
            dob_values  = consumer_data.get("dob")
            dob         = get_dob(dob_values)
            age         = get_age(dob_values)
            gender      = consumer_data.get("gender")

            Consumer.objects.create(
                user=user, interests=interest_data, dob=dob, age=age, gender=gender)

                User.objects.filter(pk=user.pk).update(is_consumer=True)
            elif request.data.get('is_business') == 'True':
                Business.objects.create(
                    user=user, **request.data.get('additional'))
                User.objects.filter(pk=user.pk).update(is_business=True)
    
            # if serializer.is_valid():
            #     user = send_verification_email(request, serializer)
    
    
            # email sending for confirmation
            email_subject   = 'Activate your account'
            email_body      = 's'
    
            send_mail(
                email_subject,
                email_body,
                settings.DEFAULT_FROM_EMAIL,
                user.email,,
            )
    
            return Response("user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1])

注册序列化器

class RegisterSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    class Meta:
        model = User
        fields = ('username', 'email', 'password',
                  'is_consumer', 'is_business')
        extra_kwargs = 'password': 'write_only': True
        model = Consumer
        fields = ('user','interests')

    def create(self, validated_data):
        user_data = validated_data
        user = User.objects.create_user(user_data.get('username'),
                                        user_data.get('email'),
                                        user_data.get('password'))

        consumer = Consumer.objects.create(user=user, interests=validated_data.get('interests'))
        consumer.save()
        return user

兴趣序列化器

class InterestsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Interests
        fields = ('technology', 'sports', 'health', 'diy', 'gaming', 'music', 'books', 'art',
                  'science', 'architecture', 'business', 'history', 'finance', 'biology', 'languages')

用户模型

class User(AbstractUser):
    email = models.CharField(max_length=100, unique=True)
    #token = models.CharField(max_length=150, unique=True)
    is_consumer = models.BooleanField(default=False)
    is_business = models.BooleanField(default=False)
    email_confirmation = models.BooleanField(default=False)

消费者模型

class Consumer(models.Model):
    GENDER_CHOICES = (
        ('Male', 'Male'),
        ('Female', 'Female'),
        ('Other', 'Other')
    )

    INTERESTS_CHOICES = (
        ('Sports', 'Sports'),
        ('Technology', 'Technology'),
        ('Health', 'Health'),
        ('DIY', 'DIY'),
        ('Gaming', 'Gaming'),
        ('Music', 'Music'),
        ('Books', 'Books'),
        ('Art', 'Art'),
        ('Science', 'Science'),
        ('Architecture', 'Architecture'),
        ('Business', 'Business'),
        ('History', 'History'),
        ('Finance', 'Finance'),
        ('Biology', 'Biology'),
        ('Languages', 'Languages')
    )

    user = models.OneToOneField(
        User, related_name='consumer', on_delete=models.CASCADE)
    interests = models.ForeignKey(Interests, related_name='interests', on_delete=models.CASCADE)
    # interests = models.ForeignKey(Interests, related_name='interests', on_delete=models.CASCADE)
    gender = models.CharField(max_length=6, choices=GENDER_CHOICES)
    dob = models.DateField(null=True)
    age = models.IntegerField(null=True)
    balance = models.FloatField(default=0)
    counter = models.IntegerField(default=0)

【问题讨论】:

消费者模型在哪里? 我已经编辑了问题并添加了它 【参考方案1】:

消费者-利益关系应该是多对多而不是一对多(ForeignKey)所以改变字段类型,进行迁移,迁移并重试。

【讨论】:

: (admin.E109) 'list_display[4]' 的值不能是 ManyToManyField。这是我得到的错误。请检查您的邮箱

以上是关于ValueError:无法分配“'interests': ['Technology', 'Sports', 'Health'] “Consumer.interests”必须是“Interests”实例的主要内容,如果未能解决你的问题,请参考以下文章

Permissions-Policy 标头出错:无法识别的功能:'interest-cohort'

/save_data/ 处的 ValueError

值错误。无法分配查询集。它必须是一个实例

django:ValueError - 无法序列化

ValueError:无法将字符串转换为浮点数:'GIAC'

ValueError("无法使用 `eval()` 评估张量: