Django AttributeError:'str'对象没有属性'pk'?

时间:2020-09-26 17:49:52

标签: django django-rest-framework

我的django项目中出现此错误,我试图以一对一关系连接django用户模型和自定义Profile模型。任何帮助将是巨大的,并高度赞赏。谢谢!

我在这里甚至尝试过WritableNestedModelSerializer,但这也不起作用!

这是我的代码。

序列化器

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ['id', 'owner', 'title', 'body']

class ProfileSerializer(WritableNestedModelSerializer):

    class Meta:
        model = Profile
        fields = ['user', 'aboutMe', 'lastAccessDate']

class UserSerializer(WritableNestedModelSerializer):
    profile = ProfileSerializer('profile')

    class Meta:
        model = User
        fields = ['pk', 'username', 'first_name', 'last_name', 'email', 'profile']

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('profile')
        # Unless the application properly enforces that this field is
        # always set, the following could raise a `DoesNotExist`, which
        # would need to be handled.
        profile = instance.profile

        instance.pk = validated_data.get('pk', instance.pk)
        instance.username = validated_data.get('username', instance.username)
        instance.email = validated_data.get('email', instance.email)
        instance.first_name = validated_data.get('first_name', instance.first_name)
        instance.last_name = validated_data.get('last_name', instance.last_name)
        instance.save()

        profile.save()

        return instance

个人资料模型

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    aboutMe = models.TextField(max_length=500, blank=True)
    lastAccessDate = models.DateTimeField()

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    else:
        instance.profile.save()

我只想更新个人资料详细信息,这是我的UserUpdateView

class UserUpdateView(UpdateAPIView):
#authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAuthenticated]
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'username'

错误

Environment:


Request Method: PUT
Request URL: http://localhost:8000/users/lasitha/update/

Django Version: 3.1
Python Version: 3.7.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'rest_framework.authtoken',
 'post.apps.PostConfig',
 'user_profile.apps.UserProfileConfig',
 'corsheaders',
 'rest_auth',
 'django.contrib.sites',
 'allauth',
 'allauth.account',
 'rest_auth.registration',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.facebook',
 'allauth.socialaccount.providers.twitter']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'user_profile.middlewares.SetLastVisitMiddleware']



Traceback (most recent call last):
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\django\views\generic\base.py", line 73, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
    raise exc
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\generics.py", line 226, in put
    return self.update(request, *args, **kwargs)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\mixins.py", line 67, in update
    serializer.is_valid(raise_exception=True)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\serializers.py", line 234, in is_valid
    self._validated_data = self.run_validation(self.initial_data)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\serializers.py", line 433, in run_validation
    value = self.to_internal_value(data)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\serializers.py", line 490, in to_internal_value
    validated_value = field.run_validation(primitive_value)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\serializers.py", line 433, in run_validation
    value = self.to_internal_value(data)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\serializers.py", line 490, in to_internal_value
    validated_value = field.run_validation(primitive_value)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\relations.py", line 153, in run_validation
    return super().run_validation(data)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\fields.py", line 566, in run_validation
    self.run_validators(value)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\fields.py", line 588, in run_validators
    validator(value, self)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\validators.py", line 72, in __call__
    queryset = self.exclude_current_instance(queryset, instance)
  File "C:\Users\janitha\anaconda3\envs\djangoEnv\lib\site-packages\rest_framework\validators.py", line 60, in exclude_current_instance
    return queryset.exclude(pk=instance.pk)

Exception Type: AttributeError at /users/lasitha/update/
Exception Value: 'str' object has no attribute 'pk'

2 个答案:

答案 0 :(得分:0)

请尝试通过以下方式进行纠正:

function addToStorage(key, val){
    let obj = {};
    obj[key] = val;

    chrome.storage.local.set( obj, function() {
      if(chrome.runtime.lastError) {
        console.error(
          "Error setting " + key + " to " + JSON.stringify(val) +
          ": " + chrome.runtime.lastError.message
        );
      }
      chrome.runtime.sendMessage({status: "Storage Updated"}, function (responce) {
          console.log(responce);
      })
    });
}

答案 1 :(得分:0)

在创建两个单独的ProfileSerializer,一个用于UserSerializer,另一个用于查看配置文件后,我设法解决了该问题。 (因为我有两个分开的用户和个人资料API端点

我什至更改了每个序列化器的fields数组,并在create内添加了updateupdate_or_create_profileUserSerializer方法。

谢谢!

这是我的代码,

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['aboutMe', 'lastAccessDate']

class UserSerializer(serializers.ModelSerializer): # you can try WritableNestedModelSerializer here

    profile = ProfileSerializer('profile')

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'profile']

    def create(self, validated_data):
        profile_data = validated_data.pop('profile', None)
        user = super(UserSerializer, self).create(validated_data)
        self.update_or_create_profile(user, profile_data)
        return user

    def update(self, instance, validated_data):
        profile_data = validated_data.pop('profile', None)
        self.update_or_create_profile(instance, profile_data)
        return super(UserSerializer, self).update(instance, validated_data)

    def update_or_create_profile(self, user, profile_data):
        # This always creates a Profile if the User is missing one;
        # change the logic here if that's not right for your app
        Profile.objects.update_or_create(user=user, defaults=profile_data)

另一个ProfileSerializer用于查看个人资料

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['user', 'aboutMe', 'lastAccessDate']