带有AngularJS的可写嵌套Serializer Django Rest Framework

时间:2016-01-15 15:28:46

标签: angularjs django django-forms django-rest-framework multipartform-data

我正在尝试将Writable Nested Serializer与AngularJS一起使用。我在相关模型中有图像字段。所以它是这样的:

class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration', 'thumbnail')  # ImageField here

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')

    def create(self, validated_data):
        tracks_data = validated_data.pop('tracks')
        album = Album.objects.create(**validated_data)
        for track_data in tracks_data:
            Track.objects.create(album=album, **track_data)
        return album

现在我想在他们提到的文档中发布数据 -

>>> data = {
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': [
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
    ],
}
>>> serializer = AlbumSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<Album: Album object>

如何使用AngularJS实现相同目的。我试图在AngularJS中使用FormData做同样的事情。但它将嵌套对象作为unicode而不是list返回。

如何在嵌套模型中使用带有imagefield的AngularJS表单发布数据。我甚至无法复制上述情况,因为Angular在request.data -

中这样返回
{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': "[
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
    ]",  # note that list here is unicode instead of list
}

应该怎么做?

编辑:

angular
.module('myapp')
.factory('submissionsSvc',function($http,$q){
    return{
        addAlbumTrack : function(){
            $http({
                    method: 'POST',
                    url: '/url',
                    data    : data,  
                    headers : { 'Content-Type': undefined },
                  }).
                    success(function(data, status, headers,config){
                      //deferred.resolve(data);
                    }).
                    error(function(data, status, headers,config){
                      //deferred.reject(status);
                    });
                }
            }
            }

表格数据

$scope.submitAlbumTracks = function(){
    var fd = new FormData();
    fd.append("album_name", $scope.albumTrack.album_name);
    fd.append("artist", $scope.albumTrack.artist);
    fd.append("tracks", $scope.albumTrack.tracks);
    submissionsSvc.addAlbumTrack(fd).then(function(response){
        console.log(response);
    });
}

更新: 似乎this是相关的。任何解决方案?

0 个答案:

没有答案