DRF的CurrentUserDefault未返回用户

时间:2017-06-23 20:49:55

标签: python django django-rest-framework

我有ModelSerializer。我在保存模型时尝试设置用户外键,通过create()类的update()ModelViewSet方法进行实例化。例如:

ModelViewSet:

def create(self, request):
    serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list))
    if not serializer.is_valid():
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    serializer.save()
    return Response(serializer.data, status=status.HTTP_201_CREATED)

串行

def process_foreign_keys(self, validated_data):
    """ Simplified for SO example """
    profile = get_object_or_404(Profile, fk_user=CurrentUserDefault())
    validated_data['profile'] = profile
    return validated_data

def create(self, validated_data):
    """ Create a Product instance. Routed from POST via DRF's serializer """
    validated_data = self.process_foreign_keys(validated_data)
    return Product.objects.create(**validated_data)

该代码无效 - 它会在get_object_or_404行引发异常:

  

int()参数必须是字符串,类字节对象或数字,而不是' CurrentUserDefault'

如果我在ModelSerializer.create()方法中添加一些调试语句,我会得到奇怪的东西:

currentuser = CurrentUserDefault()

# Expect <class django.contrib.auth.models.User>, get <class 'rest_framework.fields.CurrentUserDefault'>
print("currentuser type " + str(type(currentuser)))

# Causes AttributeError: 'CurrentUserDefault' object has no attribute 'user' 
print("currentuser is " + str(currentuser.__call__()))

# Causes AttributeError: 'ProductSerializer' object has no attribute 'request'
print("currentuser is " + str(self.request.user))

这一切都是在用户登录时完成的,因此不是AnonymousUser问题。

我搞砸了什么?如何通过serializer create的{​​{1}} / update方法实例化ModelViewSet中的当前用户?

编辑:尝试使用self.get_serializer()似乎也无效。来自文档:

  

&#34; HiddenField&#34;

所以我设置为HiddenField: This field will be present in validated_data but will not be used in the serializer output representation.类字段:

ModelSerializer

...然后在currentuser = serializers.HiddenField(default=serializers.CurrentUserDefault()) 方法中尝试validated_data.get('currentuser'),然后返回update

2 个答案:

答案 0 :(得分:1)

.button { background-color: #722F37; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 24px; margin: 4px 2px; cursor: pointer; display: table-cell; vertical-align: middle; }不是让用户摆脱虚空的神奇方法。它必须位于documentation

中显示的字段a的上下文中

正如@pramod指出的那样,你需要:

    <div id="quiz" align="center">
       <button class="button">Option A will go here. Option A will go here.</button>

或将CurrentUserDefault设置为字段的默认值。

答案 1 :(得分:1)

def create(self, request):
    serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list), context={"request": request})

您可以将serializer实例化更改为上述代码,并按以下方式使用它:

profile = get_object_or_404(Profile, fk_user=self.request.user)