Deep3015 Deep3015 - 2 months ago 20
Python Question

Error while saving image using Django Rest Framework with angularjs

I have two models Blogs, Photo. In Photo model I have fields 'blogs' as foreign key to Blogs model.

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'}
});
}


result:

{image: ["No file was submitted."]}

Also I want to know, is there a better way to get blogs value (Foreign Key) for Photo Model.

Answer

In js:

headers: { 'Content-Type': undefined}

This solves the problem.