nastyn8 nastyn8 - 5 months ago 49
Python Question

Invalid file error when trying to open file - Requests and Django

I'm using requests module with Django and trying to send a file from a form but when I do I get "invalid file :" error when I try to open the file. I think that it's only trying to open the filename as a string instead of opening the actual file. How can I go about opening the actual file from the form instead of just trying to open the filename, so I can send it as a payload?

class AddDocumentView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
login_url = reverse_lazy('users:login')
form_class = FileUploadForm
template_name = 'docman/forms/add-document.html'
success_message = 'Document was successfully added'

def form_valid(self, form):
pk = self.kwargs['pk']
user = get_object_or_404(User, pk=pk)
file =
file.user = user
if not self.post_to_server(file,
return super(AddDocumentView, self).form_valid(form)

def post_to_server(self, file, cid):
url = ''
headers = {'token': '333334wsfSecretToken'}

# I get error here when trying to open file
payload = {'file': open(file, 'rb'), 'client_id': cid}
r =, data=payload, headers=headers)
if r.status_code ==
return True
return False


open(file, 'rb') receiving django model object from file = line, not file. send original file. You can do something like

file = self.request.FILES.get('name')


No need to call open on the file, it's already open. open(file, 'rb') takes file path. the file is already open from above lines just use that. best practice

files = {'file': file}
r =, files=files, data=payload)