在我的视图(CreateView)中,我重写了def create方法,但是在我的验证中,我无法通过self.context.get('request').user
来登录用户,因此,如何使用户登录到我的验证中?
更新:
错误是:
line 293, in validate
user = self.context.get('request').user
AttributeError: 'NoneType' object has no attribute 'user'
更新2
class OrderAPIPost(CreateAPIView):
permission_classes = (permissions.IsAuthenticated, )
serializer_class = MultipleOrderSerializer
queryset = Order.objects
def create(self, request, *args, **kwargs):
write_serializer = MultipleOrderSerializer(data=request.data)
write_serializer.is_valid(raise_exception=True)
orders = write_serializer.data.get('items')
orders = list(map(lambda order: Order.create_order(order, self.request.user), orders))
read_serializer = list(map(lambda order: OrderSerializerList(order), orders))
read_serializer = list(map(lambda order: order.data, read_serializer))
return Response(read_serializer, status=status.HTTP_201_CREATED)
答案 0 :(得分:1)
因此,从我在您的代码中看到的,您正在手动创建序列化器,而无需添加上下文。在大多数情况下,允许CreateView
自己创建序列化程序就足够了,但是如果您确实需要自己创建序列化程序,则需要记住传递上下文。像这样的东西:
context = {'request': self.request}
write_serializer = MultipleOrderSerializer(data=request.data, context=context)
您可以检查视图的get_serializer()
方法以查看如何正确创建序列化程序。我真的建议您重构代码,并尝试使用现有的解决方案来创建序列化程序