10

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.

1
  • The forms accept a POST request, and would do exactly what you would want to do. Commented Jun 11, 2011 at 9:22

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

It's more secure if "@csrf_exempt" can be removed. :)
@ybdesire csrf is designed for forms. A different authentication method should be considered for API calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.