0

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.

3
  • did you try with serializer.save(blogs=Blogs.objects.latest('id'), image=self.request.FILES['image'])? Commented Sep 11, 2016 at 20:20
  • check your submitted formdata also has image file. Commented Sep 12, 2016 at 3:46
  • @Rohan Form Data 'Content-Disposition: form-data; name="image"; filename="bread.jpg" Content-Type: image/jpeg ' Commented Sep 12, 2016 at 4:02

1 Answer 1

0

In js:

headers: { 'Content-Type': undefined}

This solves the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.