class Post(models.Model):
id = models.CharField(max_length=36, primary_key=True, default=uuid.uuid4())
profile = models.ForeignKey(Profile)
created_at = models.BigIntegerField(default=int(time.time()))
edited_at = models.BigIntegerField(default=int(time.time()))
image = models.FileField(upload_to='/images/')
title = models.CharField(max_length=50)
description = models.CharField(max_length=250)
class MultiPartResource(object):
def deserialize(self, request, data, format=None):
if not format:
format = request.Meta.get('CONTENT_TYPE', 'application/json')
if format == 'application/x-www-form-urlencoded':
return request.POST
if format.startswith('multipart'):
data = request.POST.copy()
data.update(request.FILES)
return data
return super(MultiPartResource, self).deserialize(request, data, format)
class PostResource(MultiPartResource, ModelResource):
profile = fields.ForeignKey(ProfileResource, 'profile')
class Meta:
queryset = Post.objects.all()
resource_name = 'post'
allowed_methods = ['get', 'post']
authorization = Authorization()
curl -F profile="/api/profile/e52f5ddc-d005-4d22-ae49-984a32012fdd/" -F image="pic2.jpg" -F title="post" -F description="some description" http://localhost/api/post/ -v
使用文件名在数据库中创建对象,但磁盘上没有文件。
答案 0 :(得分:2)
// PostResource需要一个额外的字段,属性的值应该与模型中的字段名称匹配
image = fields.FileField(attribute='image')
// upload_to参数应包含已存在的位置,否则您将收到错误
image = models.FileField(upload_to='/images/')
// curl命令中使用的图像字段需要更改为如下所示
-F "image=@someimage.jpg"
如果其他人在将此问题付诸实施时遇到问题,我希望您偶然发现此帖并找到解决方案。