Django Rest Framework HTML POST 表单报错 提交后必填
Django Rest Framework HTML POST form giving error message This field is required after submitting
我的 models.py 是
class Genre(models.Model):
genre = models.CharField(max_length=200)
def __str__(self):
return self.genre
class Movies(models.Model):
popularity=models.DecimalField(max_digits=5, decimal_places=2)
director = models.CharField(max_length=200)
genre = models.ManyToManyField(Genre, blank=True, null=True)
score= models.DecimalField(max_digits=5, decimal_places=2)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
这是我的序列化器和视图集
# Serializers define the API representation.
class MoviesSerializer(serializers.ModelSerializer):
#genre = serializers.StringRelatedField(many=True)
genre = serializers.SlugRelatedField(queryset=Genre.objects.all(),many=True,slug_field='genre' )
class Meta:
model = Movies
fields = ('popularity', 'director', 'genre', 'score','name')
# ViewSets define the view behavior.
class MovieViewSet(viewsets.ModelViewSet):
queryset = Movies.objects.all()
serializer_class = MoviesSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'movies', MovieViewSet)
我以 Superuser
身份登录时能够看到 HTML POST 表单。但是在提交 HTML POST
表单时收到错误消息 This field is required
。代码中的错误是什么。感谢您提前提供帮助。
您应该为此使用 SlugRelatedField 而不是 StringRelatedField。
我的 models.py 是
class Genre(models.Model):
genre = models.CharField(max_length=200)
def __str__(self):
return self.genre
class Movies(models.Model):
popularity=models.DecimalField(max_digits=5, decimal_places=2)
director = models.CharField(max_length=200)
genre = models.ManyToManyField(Genre, blank=True, null=True)
score= models.DecimalField(max_digits=5, decimal_places=2)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
这是我的序列化器和视图集
# Serializers define the API representation.
class MoviesSerializer(serializers.ModelSerializer):
#genre = serializers.StringRelatedField(many=True)
genre = serializers.SlugRelatedField(queryset=Genre.objects.all(),many=True,slug_field='genre' )
class Meta:
model = Movies
fields = ('popularity', 'director', 'genre', 'score','name')
# ViewSets define the view behavior.
class MovieViewSet(viewsets.ModelViewSet):
queryset = Movies.objects.all()
serializer_class = MoviesSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'movies', MovieViewSet)
我以 Superuser
身份登录时能够看到 HTML POST 表单。但是在提交 HTML POST
表单时收到错误消息 This field is required
。代码中的错误是什么。感谢您提前提供帮助。
您应该为此使用 SlugRelatedField 而不是 StringRelatedField。