0
私は2つのモデルを持っていますブログ、写真。フォトモデルでは、Blogsモデルの外部キーとしてフィールド 'ブログ'があります。Django Rest Frameworkを使って画像を保存中にエラーが発生しました
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'}
});
}
結果:
{画像:[「いいえ、ファイルが提出されなかった」]}
また、私が知りたい、写真のモデルのブログ値(外部キー)を取得するためのより良い方法があります。 JSで
あなたは 'serializer.save(blogs = Blogs.objects.latest( 'id')、image = self.request.FILES ['image'])'を試しましたか? – arcegk
提出したフォームデータをチェックすると、イメージファイルもあります。 – Rohan
@Rohanフォームデータ 'Content-Disposition:フォームデータ。名前= "イメージ";ファイル名= "bread.jpg" コンテンツタイプ:image/jpeg ' –