【问题标题】:REST framework puts the data but doesn't change themREST 框架放置数据但不更改它们
【发布时间】:2015-09-04 05:06:51
【问题描述】:

我正在使用rest框架来序列化我的数据,并且我成功地创建了一个序列化器,如下所示,但是当我填写表格并发送它时,它发送但我的数据没有改变,甚至没有一个错误!并且空白字段保持空白不变!我该怎么办?

Serializer.py:

class UserProfileSignUpSerializer(serializers.ModelSerializer):
    verification_code = serializers.ReadOnlyField(read_only=True)

    class Meta:
        model = UserProfile
        fields = ['id', 'gender', 'birthday', 'country', 'city', 'street_address', 'state', 'about', 'social_links',
                  'location', 'avatar', 'verification_code']


class UserSignUpSerializer(serializers.ModelSerializer):
    user_profile = UserProfileSignUpSerializer()

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username', 'user_profile')

    def update(self, instance, validated_data):
        user_profile_data = validated_data.pop('user_profile')
        for attr, value in user_profile_data.items():
            setattr(instance, attr, value)
        for attr, value in validated_data.items():
            setattr(instance.user_profile, attr, value)
        # UserProfile.objects.create(user=instance, **user_profile_data)
        instance.save()
        instance.user_profile.save()
        return instance

Views.py:

class UserSignupDetail(generics.RetrieveUpdateAPIView):
    serializer_class = UserSignUpSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,)

    def get_queryset(self):
        pk = self.kwargs['pk']
        signup = User.objects.filter(pk=pk)
        return signup

Permission.py:

此文件指定权限级别,因为只有所有者才能编辑对象。

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Custom permission to only allow owners of an object to edit it.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.


        return obj.username == request.user.username

我这里有一个模型,Profile,其中存在多个对象,并且与auth.User一一对应;和一个名为 Userprofile 的子类。

模型.py

class Profile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    avatar = models.ImageField(blank=True, upload_to=get_image_path)
    street_address = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=100, blank=True)
    state = models.CharField(max_length=100, blank=True)
    country = models.CharField(max_length=100, blank=True)
    persian_address = models.CharField(max_length=100, blank=True)
    about = models.TextField(max_length=100, blank=True)
    social_links = models.TextField(blank=True)
    update = models.DateTimeField(auto_now=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    location = GeopositionField()


# User Profile
class UserProfile(Profile):
    user = models.OneToOneField(User, related_name='user_profile')
    gender = models.CharField(choices=sex, max_length=1)
    birthday = models.DateField(blank=True, null=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,11}$', message="Phone number must be entered in the format: "
                                                                   "'9123456789'. Up to 15 digits allowed.")
    call_no = models.CharField(validators=[phone_regex], max_length=15, blank=False, default='9123456789')
    verification_code = models.CharField(default=generator(4), max_length=5, blank=False)
    is_verified = models.BooleanField(default=False)

【问题讨论】:

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


    【解决方案1】:

    您是否检查过是否尝试过使用“POST”。还要确保表单没有与旧数据一起缓存,我自己也遇到过这个问题。

    【讨论】:

    • 我必须使用'PUT',因为我想更新信息,但我该怎么做Also make sure the form is not cached with the old data
    • 如果你的意思是在浏览器中,我按F5几次,但没有变化!
    • 一种简单的方法是获取表单并添加一些随机查询字符串编号,以便您知道 get 正在返回一个新值。所以如果是 GET user/userid=12345 则将其更改为 GET user/userid=12345&rnd=23048290
    【解决方案2】:

    我将我的 serializer.py 更改为以下内容,它可以正常工作:

    class UserSignUpSerializer(serializers.ModelSerializer):
        user_profile = UserProfileSignUpSerializer()
    
        class Meta:
            model = User
            fields = ('first_name', 'last_name', 'username', 'user_profile')
    
        def update(self, instance, validated_data):
            user_profile_data = validated_data.pop('user_profile')
    
            for attr, value in validated_data.items():
                setattr(instance, attr, value)
    
            instance.save()
            try:
                UserProfile.objects.get(user=instance)
                for attr, value in user_profile_data.items():
                    setattr(instance.user_profile, attr, value)
            except ObjectDoesNotExist:
                UserProfile.objects.create(user=instance, **user_profile_data)
            instance.user_profile.save()
            return instance
    

    【讨论】:

      猜你喜欢
      • 2018-07-24
      • 2018-06-02
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多