Search code examples
djangodjango-rest-frameworkdjango-testingdjango-unittestdjango-tests

Django upload file test returns 301


I am trying to test an API post call which allow file uploading but I cannot get it to work, I am always receiving a 301

with open('video.mp4') as f:
    data = {'file': f}
    response = self.client.post('/api/upload_file', data, format='multipart')

The returned response is a 301

HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/api/v1/assets/upload_file/"

I make sure the self.client is authenticated and the rest of the tests run correctly

self.client = APIClient()
self.client.force_authenticate(user=self.user)

Solution

  • You're missing the trailing slash in your test, so Django is automatically redirecting because you have APPEND_SLASH = True.

    To fix the problem, change your code to:

    self.client.post('/api/upload_file/', data, format='multipart')