Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django Rest框架&x27;str';对象没有属性';id';_Python_Django_Python 3.x_Django Rest Framework - Fatal编程技术网

Python Django Rest框架&x27;str';对象没有属性';id';

Python Django Rest框架&x27;str';对象没有属性';id';,python,django,python-3.x,django-rest-framework,Python,Django,Python 3.x,Django Rest Framework,我正在DRF中创建一个呼叫以发布到该站点。我有点不明白为什么会出现这个错误。我不明白为什么这是一个str。我知道有类似的帖子,但他们仍然逃避解决方案 错误 AttributeError: 'str' object has no attribute 'id' [03/Apr/2018 10:55:12] "POST /api/user/UserProfile/1/ HTTP/1.1" 500 83982 serializer.py看起来像,如果我删除instance.id,我会得到相同的错误,但

我正在DRF中创建一个呼叫以发布到该站点。我有点不明白为什么会出现这个错误。我不明白为什么这是一个str。我知道有类似的帖子,但他们仍然逃避解决方案

错误

AttributeError: 'str' object has no attribute 'id'
[03/Apr/2018 10:55:12] "POST /api/user/UserProfile/1/ HTTP/1.1" 500 83982
serializer.py看起来像,如果我删除instance.id,我会得到相同的错误,但只会出现在下一行

from rest_framework import serializers
from api.models import UserProfile
from django.contrib.auth.models import User


class UserProfileSerializer(serializers.Serializer):
    # id = serializers.UUIDField()
    class Meta:
        model = UserProfile

    def create(self, validated_data):
        return UserProfile.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.id = validated_data.get('profile_id', str(instance.id))
        instance.user_id = validated_data.get('user_id', instance.user_id)
        instance.save()
        return instance
查看

@csrf_exempt
def user_profile_list(request, user_id):
    try:
        userid = user_id
    except userid.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        uprofile = UserProfile.objects.all().values()
        list2 = list(uprofile)
        return JsonResponse(list2, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserProfileSerializer(userid, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)
url.py

url(r'^api/user/UserProfile/(?P<user_id>[0-9]+)/$', userprofile.user_profile_list),
url(r'^api/user/UserProfile/(?P[0-9]+)/$),UserProfile.user\u profile\u列表),

您传递给序列化程序
用户ID
,而不是用户对象。要使用序列化程序更新对象,应将实例作为第一个参数传递。将视图更改为:

elif request.method == 'POST':
    data = JSONParser().parse(request)
    user = User.objects.get(id=userid)
    serializer = UserProfileSerializer(user, data=data)
    ...

属性错误

AttributeError: 'str' object has no attribute 'id'
[03/Apr/2018 10:55:12] "POST /api/user/UserProfile/1/ HTTP/1.1" 500 83982
问题出在
serializer=UserProfileSerializer(userid,data=data)
行中,您将
userid
传递给序列化程序,而不是用户或用户配置文件实例,或者是因为我不太清楚逻辑(使用UserProfileSerializer但更新用户实例?)

改进

您试图用代码完成的任务可以以一种更简单的方式完成:

  • 使用序列化程序而不是序列化程序
  • 使用基于功能的视图而不是基于功能的视图(
    user\u profile\u list
  • 使用ModelSerializer和ModelViewSet的通用版本应符合以下要求:

    序列化程序.py

    from rest_framework import serializers
    from api.models import UserProfile
    
    
    class UserProfileSerializer(serializers.ModelSerializer):
        class Meta:
            model = UserProfile
            # preferably listing the fields to avoid any code breaking
            # if you add fields to the model later on
            fields = '__all__'
    
    views.py

    from rest_framework import viewsets
    
    from api.serializers import UserProfileSerializer
    from api.models import UserProfile
    
    
    class UserProfileViewSet(viewsets.ModelViewSet):
        queryset = UserProfile.objects.all()
        serializer_class = UserProfileSerializer
    

    我强烈建议您仔细阅读,如果您了解应用程序的哪些部分已经在DRF中实现,并且只需少量代码即可直接使用,那么您将节省大量的开发时间

    错误信息很清楚,调试你的代码,看看为什么
    instance
    会得到
    str
    .django noob…不知道怎么做请阅读,这是一个很好的工具!