#django #python-3.x
#django #python-3.x
Вопрос:
Я пытаюсь сгенерировать PDF-файл, используя записи базы данных модели django (в основном данные были введены с помощью html-формы и отправлены в базу данных некоторым представлением) и сохранить его в поле file той же модели. Но ни одно из опубликованных решений, связанных с этой темой, не показывает, как выполнить эту задачу (или, возможно, я не могу это выяснить).
Это мое мнение, связанное с сохранением записи формы в базе данных
def apply_purchase(request):
current_user = get_object_or_404(User, username=request.user.username)
print(current_user)
user_details = ExtraInfo.objects.all().filter(user=current_user).first()
print(user_details)
user_type = HoldsDesignation.objects.all().filter(user=current_user).first()
print(user_type)
usertype=str.split(str(user_type))
print(usertype)
# Academics Admin Check
user=usertype[0]
#desig_id = Designation.objects.all().filter(name='Faculty')
#print(desig_id)
if(user == "student"):
return HttpResponse('You are not authorised to view this page')
if request.method == 'POST':
item_name=request.POST.get('item_name')
quantity=request.POST.get('quantity')
expected_cost=int(request.POST.get('expected_cost'))
if expected_cost >=25000 and expected_cost <= 250000 :
local_comm_mem1_id=request.POST.get('local_comm_mem1_id')
local_comm_mem2_id=request.POST.get('local_comm_mem2_id')
local_comm_mem3_id=request.POST.get('local_comm_mem3_id')
nature_of_item1= 1 if request.POST.get('nature_of_item1') == 'on' else 0
nature_of_item2= 1 if request.POST.get('nature_of_item2') == 'on' else 0
purpose=request.POST.get('purpose')
expected_purchase_date=request.POST.get('expected_purchase_date')
a = apply_for_purchase.objects.create(
item_name=item_name,
quantity=int(quantity),
expected_cost=expected_cost,
nature_of_item1=nature_of_item1,
nature_of_item2=nature_of_item2,
purpose=purpose,
# budgetary_head_id = budgetary_head_id,
# inspecting_authority_id=inspecting_authority_id,
expected_purchase_date= expected_purchase_date,
indentor_name=user_details,
)
a.save()
Я новичок в django, поэтому буду признателен за любую помощь
Ответ №1:
Согласно документации, вы должны быть в состоянии достичь этого с помощью ReportLab. Чтобы вывести PDF так, как вы этого хотите, вам придется настроить способ отображения PDF.
Вот фрагмент короткого кода из ReportLab, который, надеюсь, то, что вам нужно.
from django.http import HttpResponse
from rlextra.rml2pdf import rml2pdf
import cStringIO
def getPDF(request):
"""Returns PDF as a binary stream."""
# Use your favourite templating language here to create the RML string.
# The generated document might depend on the web request parameters,
# database lookups and so on - we'll leave that up to you.
rml = getRML(request)
buf = cStringIO.StringIO()
rml2pdf.go(rml, outputFileName=buf)
buf.reset()
pdfData = buf.read()
response = HttpResponse(mimetype='application/pdf')
response.write(pdfData)
response['Content-Disposition'] = 'attachment; filename=output.pdf'
return response
Комментарии:
1. не могли бы вы, пожалуйста, подробнее рассказать о том, как настроить pdf?