我有一个视图,该视图会为用户选择的任何“参考号”生成一个.docx文件-每当生成doc时,我都希望将该文件保存到我的Orders模型中。
models.py
#model where I'd like to save the doc each time it gets generated
class Orders(models.Model):
reference = models.CharField(max_length=50, unique=True, error_messages={'unique':"This reference id has already been used"})
ultimate_consignee = models.ForeignKey(Customers, blank=True)
ship_to = models.CharField(max_length=500, blank=True)
vessel = models.CharField(max_length=100, blank=True)
...
order_file = #not sure what data type to use here
views.py
#view generating the .docx
def docjawn(request):
reference = request.POST.get('Reference_IDs')
referenceid = reference
manifest = Manifests.objects.all().filter(reference__reference=referenceid)
order = Orders.objects.get(reference=reference)
doc = DocxTemplate("template.docx")
totalCNF = 0
totalFOB = 0
for item in manifest:
totalCNF += item.cases * item.CNF
totalFOB += item.cases * item.FOB
context = {
'ultimate_consignee' : order.ultimate_consignee,
'reference' : order.reference,
'ship_to' : order.ship_to,
'terms' : order.terms,
'date' : "12",
'ship_date' : "7/4/19",
'vessel' : order.vessel,
'POE' : order.POE,
'ETA' : order.ETA,
'booking_no' : order.booking_no,
'manifest' : manifest,
'totalCNF' : totalCNF,
'totalFOB' : totalFOB,
}
doc.render(context)
doc_io = io.BytesIO() # create a file-like object
doc.save(doc_io) # save data to file-like object
doc_io.seek(0) # go to the beginning of the file-like object
response = HttpResponse(doc_io.read())
# Content-Disposition header makes a file downloadable
response["Content-Disposition"] = "attachment; filename=generated_doc.docx"
# Set the appropriate Content-Type for docx file
response["Content-Type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
return response
好的,因此当访问上方的视图时,系统应生成文件并将其保存到Orders模型中,其中WHERE reference = reference_id。这可能吗?有什么建议么?我真的不知道如何开始尝试将两者连接起来。
最佳答案
看来您的观点已接近完成您想要的事情。在模型中,为FileField
添加order_file
:
class Orders(models.Model):
...
order_file = models.FileField(upload_to='path/to/storage/', null=True, blank=True)
然后在您的视图中,将正确创建的
BytesIO
对象包装到order_file
对象中,并使用正确的Orders
将其保存到reference_id
对象的File
字段中:from django.core.files import File
def docjawn(request):
reference = request.POST.get('Reference_IDs')
manifest = Manifests.objects.all().filter(reference__reference=reference)
order = Orders.objects.get(reference=reference)
# Generate doc file
...
doc_io = io.BytesIO()
doc.save(doc_io)
doc_io.seek(0)
# Save the BytesIO to the field here
order.order_file.save("generated_doc.docx", File(doc_io))
response = HttpResponse(doc_io.read())
response["Content-Disposition"] = "attachment; filename=generated_doc.docx"
response["Content-Type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
return response
关于python - 如何在Django模型中创建和保存文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57486796/