python - Django-Rest-Framework 'str' 对象没有属性 'id'

标签 python django python-3.x django-rest-framework

我正在 DRF 中创建一个调用以 POST 到该网站。我有点困惑为什么会出现这个错误。我不明白为什么这期望它是一个 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)

urls.py

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

最佳答案

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

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

关于python - Django-Rest-Framework 'str' 对象没有属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49635654/

相关文章:

python - Scrapy 好像没有做 DFO

python - 向自定义 Django management/manage.py 命令添加确认步骤

Python - 包不是相对于当前目录的吗?

python - 在 Python 中使用元组更新 2D 列表

python - 尝试使用 pyspark 从 S3 获取数据时出现空指针异常

python json schema返回所有验证错误

python - 使用 CNN 模型中的 channel 均值和标准差对训练数据进行归一化

Django:仅更新 UpdateView 中已更改的字段

django - 可以在 Django 抽象模型中使用多重继承吗?

python - 按索引覆盖列表切片中的值