Django Rest Framework HTML POST表单给出错误消息提交后需要此字段

时间:2015-11-22 09:12:36

标签: python django django-models django-rest-framework django-serializer

我的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

这是我的Serializer和viewset

# 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)

我以[{1}}身份登录时能够看到HTML POST表单。但在提交Superuser表单时收到错误消息HTML POST。代码中的错误是什么?感谢您提前帮助。

enter image description here enter image description here

1 个答案:

答案 0 :(得分:1)

您应该使用SlugRelatedField而不是StringRelatedField。