使用带有angularjs的Django Rest Framework保存图像时出错

时间:2016-09-11 20:05:20

标签: python angularjs django django-rest-framework

我有两个模特博客,照片。在Photo模型中,我有字段'博客'作为Blogs模型的外键。

models.py:

def content_file_name(instance, filename):
    custt=str(datetime.now())
    return '/'.join(['content', instance.blogs.slug,custt, filename])

class Photo(models.Model):
    blogs = models.ForeignKey(Blogs)
    image = models.ImageField(upload_to=content_file_name)

class Blogs(models.Model):
    author = models.ForeignKey(CustomUser)
    title=models.CharField(max_length=100)
    postedin=models.ForeignKey(Posted)
    tags= models.ManyToManyField(Tags)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    slug=models.SlugField(max_length=255,unique=True)

    def __unicode__(self):
        return '{0}'.format(self.title)

views.py:

class PhotoViewSet(viewsets.ModelViewSet):
    queryset=Photo.objects.all()
    serializer_class = PhotoSerializer

    def perform_create(self,serializer):
        serializer.save(blogs=Blogs.objects.latest('id'))
        return super(PhotoViewSet,self).perform_create(serializer)

serializers.py:

class PhotoSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(
    max_length=None, use_url=True,
    )
    class Meta:
        model = Photo
        read_only_fields = ("blogs",)

JS:

function uploadpic(image) {
var fd = new FormData();
fd.append( 'image', image );
  return $http.post('/api/v1/uploadpic/',fd, {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
}

结果:

{image:["没有提交文件。"]}

另外我想知道,是否有更好的方法来获取Photo Model的博客价值(外键)。

1 个答案:

答案 0 :(得分:0)

在js:

headers: { 'Content-Type': undefined}

这解决了这个问题。