英文:
Can I provide automatically current user in Django rest API like this?
问题
我有一个Django REST API。在我的模型中,我有一个用户作为外键。当我进行POST请求时,我不希望用户需要提供自己的用户信息。但是如果用户不提供用户凭据,序列化器将无效,然后不会保存。我发现可以在验证之前使用initial_data
访问序列化的数据,所以我像这样做来自动保存通过提供的令牌的用户。用户需要提供除了他自己的用户之外的所有信息。这样做可以吗,还是我在做一些不推荐的事情?
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_mesure(request):
serializer = MesureSerializer(data=request.data)
serializer.initial_data['user'] = request.user.id
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
英文:
I have a Django rest api. In my model I have a user as a foreign key. When I do a post with the, I do not want that the user needs to provide his own user. But if the user does not provide his user credentials, the serializer won't be valid and then won't be saved. I have found that we can access to serialized dat before validation with initial_data
so I am doing like this to save the user automatically from the token provided. The user need to provide everything except his own user. Is it ok or am I doing something not recommended ?
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def add_mesure(request):
serializer = MesureSerializer(data=request.data)
serializer.initial_data['user'] = request.user.id
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
答案1
得分: 1
因为您已经将令牌作为用户验证的一种方式,所以可以从序列化器中省略user
字段(否则用户可能会填写其他人的ID,例如),然后在保存期间将请求对象传递给序列化器以从中获取用户。像这样:
#序列化器
class MesureSerializer(ModelSerializer):
class Meta:
exclude = ['user',]
...
def create(self, validated_data):
validated_data['user'] = self.context['request'].user
return super().create(validated_data)
此外,要传递请求的值,您可以使用context序列化器的参数。
#视图
serializer = MesureSerializer(data=request.data, context={'request': request})
英文:
As you are already taking the token as a form of user verification, hence you can omit the user
field from serializer (otherwise user might put someone else's id for example) and then pass the request object to serializer to get user from it during saving. Like this:
#serializer
class MesureSerializer(ModelSerializer):
class Meta:
exclude = ['user',]
...
def create(self, validated_data):
validated_data['user'] = self.context['request'].user
return super().create(validated_data)
Also, to pass the value of request, you can use context parameter of the serializer.
#view
serializer = MesureSerializer(data=request.data, context={'request':request})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论