On Sun, 15 Jun 2014 18:47:29 -0700 (PDT)
Taylor Marks <
taylo...@ranttapp.com> wrote:
> Hello,
>
> I would like to allow users to upload an arbitrary number of files with
> their HTTP POSTs.
That is relatively simple and it's not actually DRF related. You can use
views DRF provides but you need to handle this manually.
> So I believe the first step is I need an APIView that, in its post method,
> passes request.FILES to a serializer. That serializer will then need to
> write to a model. The model will ultimately put those files into FileFields.
You can do it that way, but it's simpler to bypass DRF in this.
> Here's my problem - I need to be able to handle an arbitrary number of
> files. My understanding is that each FileField can only hold a single file.
> Further, models need to have a fixed number of files - there's no way to
> have an arbitrary number of fields (possibly on account of a limitation of
> the backing store, MySQL).
Yes, you would be storing your files using standard Django file upload mechanism.
Do not even try to save files in the database - it will blow up to your face eventually.
You would need to have first model that stores your file(s):
class Attachment(models.Model):
'''
Files attached to katulupa_license
'''
target = models.ForeignKey('myapp.TargetModel', related_name='attachments')
file = models.FileField(upload_to='attachments/')
And then a view that actually binds files to your model:
class MyAPI(APIView):
def post(self, request, target_pk=None, format=None):
"""
Receive uploaded files
"""
attachments = request.FILES.getlist('file', [])
for attachment in attachments:
a = Attachment(target=target_pk, file=attachment)
a.save()
data = {'success': True }
# Hack to render JSON as text/html. This is required for "ajax" fileuploads
request.accepted_renderer = renderers.JSONRenderer()
return Response(data, content_type='text/html')
The hack part is there because there is no such thing as a json uploads. Most JS frameworks
implements it as an upload through hidden frame and they require response usually in JSON format
that is rendered as a text/html.
If you're not using ajax to upload files, or your framework response expectations is different, or you
like to pass uploaded file links for example that's the place to do it.
You need also a url config for that view:
url(r'^api/mymodelapi/(?P<pk>\w+)/upload_files/$', MyAPI.as_view(), name='mymodelapi-upload-files')
Now the final part is to fiddle with client side - you can add multiple uploaded files, just use always
same name attribute for each file filed so Django knows how to gather them in request.FILES.
--
Jani Tiainen