I have a Django app that revolves around users uploading files, and I'm attempting to make an API. Basically, the idea is that a POST request can be sent (using curl for example) with the file to my app which would accept the data and handle it.
How can I tell Django to listen for and accept files this way? All of Django's file upload docs revolve around handling files uploaded from a form within Django, so I'm unsure of how to get files posted otherwise.
If I can provide any more info, I'd be happy to. Anything to get me started would be much appreciated.
You just need to put the field in your ModelSerializer and set content-type=multipart/form-data; in your client. BUT as you know you can not send files in json format. (when content-type is set to application/json in your client). Unless you use Base64 format.
The Django documentation for File Uploads, gives a brief understanding of the workflow of how to upload a single file using forms and importing in views. In a similar way, we can also tweak it to upload multiple files using forms and views.
Create a small view which accepts only POST and make sure it does not have CSRF protection:
forms.py
from django import forms
class UploadFileForm(forms.Form):
title = forms.CharField(max_length=50)
file = forms.FileField()
views.py
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse, HttpResponseServerError
# Imaginary function to handle an uploaded file.
from somewhere import handle_uploaded_file
@csrf_exempt
@require_POST
def upload_file(request):
form = UploadFileForm(request.POST, request.FILES)
if not form.is_valid():
return HttpResponseServerError("Invalid call")
handle_uploaded_file(request.FILES['file'])
return HttpResponse('OK')
See also: Adding REST to Django
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With