0
我使用Django的請求模塊並試圖從窗體發送文件,但是當我嘗試獲取「無效文件:」錯誤時打開文件。我認爲它只是試圖打開文件名作爲一個字符串,而不是打開實際的文件。我怎樣才能從表單打開實際的文件,而不僅僅是打開文件名,所以我可以將它作爲有效載荷發送?試圖打開文件時發生無效文件錯誤 - 請求和Django
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 = form.save(commit=False)
file.user = user
if not self.post_to_server(file, user.id):
file.delete()
return super(AddDocumentView, self).form_valid(form)
def post_to_server(self, file, cid):
url = 'https://example.herokuapp.com/api/files/'
headers = {'token': '333334wsfSecretToken'}
# I get error here when trying to open file
payload = {'file': open(file, 'rb'), 'client_id': cid}
r = requests.post(url, data=payload, headers=headers)
print(r.text)
if r.status_code == requests.codes.ok:
return True
else:
return False
明白了。我這樣做了,但我得到了同樣的錯誤,但這次它實際上是識別文件而不是字符串。 TypeError:invalid file: –
nastyn8
@ nastyn8我更新了我的答案 – MicroPyramid