我在Django中有一个用户,帖子和标签模型。标记模型与本主题无关。我可以将所有数据使用嵌套对象获取到前端。另一方面,当我想创建一个新帖子时,我将帖子数据发送到django,在django视图中,我正在尝试更新数据,将登录用户与“帖子”相关联,但当我这样做时,它会给我;
{'owner': {'username': [ErrorDetail(string='A user with that username already exists.', code='unique')]}}
错误。我该如何解决这个错误?
models.py;
class Post(models.Model):
# Post specs
title = models.CharField(max_length=100, null=False)
place = models.CharField(max_length=100, null=False)
notes = models.CharField(max_length=10000, null=False)
tags = models.ManyToManyField(Tag)
start_date = models.DateField(null=True)
end_date = models.DateField(null=True)
created_at = models.DateField(auto_now=True)
owner = models.ForeignKey(User , null = True, on_delete=models.SET_NULL)
serializers.py;
class PostSerializer(serializers.ModelSerializer):
tags = serializers.SlugRelatedField(
many=True,
queryset=Tag.objects.all(),
slug_field='name'
)
owner = UserSerializer()
class Meta:
model = Post
fields = ('title','place','notes','start_date','end_date','created_at','id','owner','tags')
顺便说一句,如果我更改 serializer.py,如所有者= 用户序列化程序,它只给出主键值。在前端,我不能用整数做任何事情,我不想为用户模型进行另一个api调用。最后查看帖子功能;
def post(self, request, format =None):
"""
Creates a post
"""
post = request.data ## copy dictionary to a variable
authenticatedUserDataAsDict = request.user.__class__.objects.filter(pk=request.user.id).values().first()
post.update( {'owner': authenticatedUserDataAsDict} ) ## attach authenticated user to post end
serializer = PostSerializer(data = post) ## serialize the dict
if serializer.is_valid():
serializer.save() ## if data valid save it.
return Response(serializer.data, status = status.HTTP_201_CREATED)
print("not valid->",serializer.errors)
return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) # if it's not raise http 400
紫衣仙女
相关分类