我正在嘗試使用 xhtml2pdf 應用程序保存生成的 PDF。我希望它將 pdf 保存到模型中。pdf 已完美創(chuàng)建,瀏覽器會下載該文件,但我不想下載,而是將其保存到模型中,在我的 models.py 中,我告訴它保存到媒體文件夾中的文件夾中。Models.py:class purchase(models.Model): purchase_id = models.AutoField(primary_key=True) transaction_date = models.DateTimeField() method_payment = models.CharField(max_length = 20) cmr_name = models.CharField(max_length = 60) cmr_address = models.CharField(max_length = 90) cmr_postcode = models.CharField(max_length = 10) cmr_tel = models.CharField(max_length = 14) cmr_email = models.CharField(max_length = 40) cmr_pod = models.FileField(upload_to='customers_id') cmr_signature = JSignatureField() receipt = models.FileField(upload_to='receipts', null=True, blank=True) added_by = models.CharField(max_length = 30) item_brand = models.CharField(max_length = 50) product = models.CharField(max_length = 100) model = models.CharField(max_length = 100) serial = models.CharField(max_length = 50) item_brand2 = models.CharField(max_length = 50) product2 = models.CharField(max_length = 100) model2 = models.CharField(max_length = 100) serial2 = models.CharField(max_length = 50) item_brand3 = models.CharField(max_length = 50) product3 = models.CharField(max_length = 100) model3 = models.CharField(max_length = 100) serial3 = models.CharField(max_length = 50) def __str__(self): return '{}'.format(self.cmr_name)管理和數(shù)據(jù)庫顯示沒有上傳任何內(nèi)容,我沒有收到任何錯誤。在views.py文件中,這些代碼行是我希望用pdf文件更新數(shù)據(jù)庫的代碼:receipt_file = File(BytesIO(pdf.content))
purchase.objects.filter(pk=purch_id).update(receipt=receipt_file)不幸的是,它沒有做任何事情。有人可以幫忙嗎?被困在這個有一段時間了。我嘗試過在 stackoverflow 和其他網(wǎng)站上看到的其他幾個答案。謝謝,任何幫助將不勝感激。Edit1:我嘗試調(diào)用 save() 而不是 update,但是沒有什么區(qū)別: receipt_file = File(BytesIO(pdf.content))
purch = purchase.objects.get(pk=purch_id)
purch.receipt = receipt_file
purch.save()Edit2:我也嘗試了幾個版本的內(nèi)容和 IOString(content) 沒有任何結果Edit3:仍然沒有答案,任何 Django 專家可能知道發(fā)生了什么事嗎?好像是這么簡單的事情..
1 回答

慕后森
TA貢獻1802條經(jīng)驗 獲得超5個贊
最后我設法使用以下代碼來做到這一點:
receipt_file = BytesIO(pdf.content) purch_upd = purchase.objects.get(pk=purch_id) purch_upd.receipt = File(receipt_file, filename) purch_upd.save()
如此簡單,不敢相信我在這個問題上堅持了這么久。
添加回答
舉報
0/150
提交
取消