How do you upload a file with a POST request on django-tastypie? [duplicate]

℡╲_俬逩灬. 提交于 2019-11-28 07:52:54

Here is way to upload file by MultiPart through django-tastypie.

Models.py

class Video(models.Model):
    video_uploader = models.ForeignKey(User)
    video = models.FileField(_('Video'), upload_to='path_to_folder/') # save file to server
    video_views = models.IntegerField(default=0)
    upload_date = models.DateTimeField(auto_now_add=True)
    video_description = models.CharField(max_length=860)
    video_title = models.SlugField()

Api.py

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 VideoResource(MultipartResource, ModelResource):
   """
   Inherit this Resource class to `MultipartResource` Class
   """
   # Assuming you know what to write here 
   ...

And then through CURL

curl -H "Authorization: ApiKey username:api_key" -F "video=/path_to_video/video.mp3" -F "video_title=video title" http://localhost:8000/api/v1/video/ -v
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!