Django 调用'Article.objects.create()时遇到'TypeError'`
我正在使用Django REST框架进行Django React项目,我试图发布一些与我的模型相关的数据 项目的列表视图和详细视图工作得很好,唯一的问题是当我试图发出POST请求时 每当我尝试在CreateAPIView中发布数据时,都会出现一个错误:Django 调用'Article.objects.create()时遇到'TypeError'`,django,reactjs,django-rest-framework,Django,Reactjs,Django Rest Framework,我正在使用Django REST框架进行Django React项目,我试图发布一些与我的模型相关的数据 项目的列表视图和详细视图工作得很好,唯一的问题是当我试图发出POST请求时 每当我尝试在CreateAPIView中发布数据时,都会出现一个错误: Got a `TypeError` when calling `Article.objects.create()`. This may be because you have a writable field on the serialize
Got a `TypeError` when calling `Article.objects.create()`. This may be because
you have a writable field on the serializer class that is not a valid argument to
`Article.objects.create()`. You may need to make the field read-only, or override
the ArticleSerializer.create() method to handle this correctly.
我搜索了过去的各种问题,但似乎没有一个能解决我的问题
这是我的序列化程序文件:
from rest_framework import serializers
from articles.models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ('id','title','content','star_count','like_count','comment_count','avatar')
这是我的视图文件
from rest_framework.generics import ListAPIView,RetrieveAPIView,CreateAPIView,UpdateAPIView,DestroyAPIView
from .serializers import ArticleSerializer
from articles.models import Article
from rest_framework import viewsets
class ArticleViewSets(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
模型文件
content = models.TextField()
comment_count = models.IntegerField(default=0,null=True,blank=True)
like_count = models.IntegerField(default=0,null=True,blank=True)
star_count = models.IntegerField(default=0,null=True,blank=True)
avatar = models.ImageField(null=True,blank=True)
def __str__(self):
return self.title
def save(self):
if not self.slug:
self.slug = slugify(self.title)
super(Article,self).save()
下面是我尝试基于django rest框架createAPIVew发出POST请求时产生的错误
Got a `TypeError` when calling `Article.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Article.objects.create()`. You may need to make the field read-only, or override the ArticleSerializer.create() method to handle this correctly.
如果不是使用POST而是使用shell、django视图或unittests,则
Article.objects.create()
是否有效?你的模型缺少标题和slug之类的接缝。你能展示整个文章模型吗?它有一个title
字段吗?是的,它有一个title-fieldClass文章(models.Model):title=models.CharField(max_-length=200)slug=models.SlugField(unique=True,null=True,blank=True)content=models.TextField()comment_-count=models.IntegerField(默认值=0,null=True,blank=True)像_-count=models.IntegerField一样(默认值=0,null=True,blank=True)star_count=models.IntegerField(默认值=0,null=True,blank=True)avatar=models.ImageField(null=True,blank=True)请更新您的问题以包含完整代码,而不是评论。