/api/img 处的 IntegrityError/"author_id" 列中的空值违反了非空约束
IntegrityError at /api/img/ null value in column "author_id" violates not-null constraint
django rest framework post请求错误
这是图像模型
class Img(models.Model):
created_at=models.DateTimeField(auto_now_add=True)
author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="img")
picture=models.ImageField(upload_to='fake_picture',null=True,blank=True)
tags = TaggableManager(blank=True)
这是模型 Img 的图像序列化程序
class ImgSerializer(serializers.ModelSerializer):
tags = TagListSerializerField(required=False)
author = serializers.StringRelatedField(read_only=True)
# post = serializers.StringRelatedField(read_only=True)
class Meta:
model=Img
fields='__all__'
views.py
class ImgViewSet(viewsets.ModelViewSet):
parser_class = (FileUploadParser,)
permission_classes =[IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly]
authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication)
queryset = Img.objects.all()
serializer_class=ImgSerializer
但是当 post 请求到那个特定的 api 端点时,从 post 人触发了键值对为
picture:image.jpg
这就是响应
IntegrityError at /api/img/
null value in column "author_id" violates not-null constraint
DETAIL: Failing row contains (4, fake_picture/2019-06-27_at_10-04-59.png, 2020-05-05 23:06:00.16071+00, null).
Request Method: POST
Request URL: http://localhost:8000/api/img/
请试试这个
class ImgViewSet(viewsets.ModelViewSet):
..........
serializer_class=ImgSerializer
.......
def perform_create(self, serializer):
serializer.save(author=serializer.context['request'].user)
django rest framework post请求错误 这是图像模型
class Img(models.Model):
created_at=models.DateTimeField(auto_now_add=True)
author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="img")
picture=models.ImageField(upload_to='fake_picture',null=True,blank=True)
tags = TaggableManager(blank=True)
这是模型 Img 的图像序列化程序
class ImgSerializer(serializers.ModelSerializer):
tags = TagListSerializerField(required=False)
author = serializers.StringRelatedField(read_only=True)
# post = serializers.StringRelatedField(read_only=True)
class Meta:
model=Img
fields='__all__'
views.py
class ImgViewSet(viewsets.ModelViewSet):
parser_class = (FileUploadParser,)
permission_classes =[IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly]
authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication)
queryset = Img.objects.all()
serializer_class=ImgSerializer
但是当 post 请求到那个特定的 api 端点时,从 post 人触发了键值对为
picture:image.jpg
这就是响应
IntegrityError at /api/img/
null value in column "author_id" violates not-null constraint
DETAIL: Failing row contains (4, fake_picture/2019-06-27_at_10-04-59.png, 2020-05-05 23:06:00.16071+00, null).
Request Method: POST
Request URL: http://localhost:8000/api/img/
请试试这个
class ImgViewSet(viewsets.ModelViewSet):
..........
serializer_class=ImgSerializer
.......
def perform_create(self, serializer):
serializer.save(author=serializer.context['request'].user)