Using Pisa to write a pdf to disk - django

I have pisa producing .pdfs in django in the browser fine, but what if I want to automatically write the file to disk? What I want to do is to be able to generate a .pdf version file at specified points in time and save it in a uploads directory, so there is no browser interaction. Is this possible?

Yes it is possible. for example, using code from Greg Newman as a starter:
from django.template.loader import get_template
from django.template import Context
import ho.pisa as pisa
import cStringIO as StringIO
import cgi
def write_pdf(template_src, context_dict, filename):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = open(filename, 'wb') # Changed from file to filename
pdf = pisa.pisaDocument(StringIO.StringIO(
html.encode("UTF-8")), result)
result.close()
You just need to call write_pdf with a template, data in a dict and a file name.

Related

Save zip to FileField django

I have a view that create two csv and my goal is to zip them and add to a model.FileField
zip = zipfile.ZipFile('myzip.zip','w')
zip.writestr('file1.csv', file1.getvalue())
zip.writestr('file2.csv', file2.getvalue())
I have tried this, the zip is upload but when I download it I have the error 'the archive is damaged or unknown format'
Mymodel.objects.create(zip = File(open('myzip.zip','rb'))
This example just worked for me,
from django.core.files import File
from django.http import HttpResponse
from .models import ZipFile
import zipfile
from django.views import View
class ZipWriteView(View):
def get(self, request, *args, **kwargs):
with zipfile.ZipFile("myzip.zip", "w") as zip_obj:
zip_obj.write("polls/views.py") # add file 1
zip_obj.write("polls/admin.py") # add file 2
with open(zip_obj.filename, "rb") as f:
ZipFile.objects.create(file=File(f))
return HttpResponse("Done")

how read specific line from csv file in django

I am trying to read csv file in django but I don't know how to achieve it. I am fresher recently joined organization and working singly, please any one help me
from django.shortcuts import render
from django.http import HttpResponse
import csv
from csv import reader
def fun(request):
with open(r"C:\Users\Sagar\Downloads\ULB_Sp_ThreePhaseUpdate.csv") as file:
reader = csv.reader(file)
ip = request.GET["id"]
flag = False
for rec in reader:
if rec[1]=="id":
return HttpResponse("MID: ",rec[2])
return render(request, "index.html")

how to show pdf from server in a Django view?

I am trying to show/read pdfs from server , but getting erros. Below I have attached my view.py . Please help me to solve it
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import PDF
def pdf_view(request):
a = PDF.objects.get(id=id)
with open('a.pdf', 'rb') as pdf:
response = HttpResponse(pdf.read(), contenttype='application/pdf')
response['Content-Disposition'] = 'filename=a.pdf'
return response
pdf.closed
you can use use Django templates to show/read pdf on sever. create 'templates' folder inside your django project. inside it create a html file which contain link of you pdf.

How to make a pop up generated file download in Django 2?

I was working on a barcode image generate system and make pdf for printing.
Here is my view.py
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch, cm
from reportlab.platypus import Paragraph
canvas.Canvas('assets/pdf_print/'+barCode+'.pdf')
c.drawImage('1.png',0.9*cm,0,3.5*cm,1.8*cm)
c.drawImage('1.png',4.8*cm,0,3.5*cm,1.8*cm)
c.drawImage('1.png',8.9*cm,0,3.5*cm,1.8*cm)
c.drawImage('1.png',12.7*cm,0,3.5*cm,1.8*cm)
c.drawImage('1.png',16.7*cm,0,3.5*cm,1.8*cm)
c.showPage()
c.save()
I save that pdf file in this path successfully using report lab
assets/pdf_print/
After saving that file in that path, I need to generate a popup download for this file.
How could I do that in Django?
just create a href link the pop with link of view which returns PDF file as response
when the user clicks on that link the browser will prompt to save the file since it is a file response
from django.http import FileResponse, Http404
def pdf_view(request):
try:
return FileResponse(open('foobar.pdf', 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()

How to use call_command with dumpdata command to save json to file

I am trying to use the call_command method to call the dumpdata command. Manually, I use it as follows to save the data to a file.
python manage.py dumpdata appname_one appname_two > /path/to/save/file.json
and it saves the json file. Now, I am in a situation where I need to call this command using the call_command method.
I am able to print out the json from the command using the following:
from django.core.management import call_command
call_command('dumpdata', 'appname_one', 'appname_two')
Is there a way I can save the given data to a file like we do it from the command line?
had to redirect sys.stdout to the file in order to achieve the above. Something like.
import sys
from django.core.management import call_command
sysout = sys.stdout
sys.stdout = open('filename.json', 'w')
call_command('dumpdata', 'appname_one', 'appname_two')
sys.stdout = sysout
An even better way is to use Django's built-in stdout redirection for their command modules. See docs here.
If you want to manipulate the stream before sending it to a file, you can also pass it a StringIO buffer:
import os
from cStringIO import StringIO
from django.core import management
def create_fixture(app_name, filename):
buf = StringIO()
management.call_command('dumpdata', app_name, stdout=buf)
buf.seek(0)
with open(filename, 'w') as f:
f.write(buf.read())
I am using Django fixture magic https://github.com/davedash/django-fixture-magic and need to dump a custom fixture. I tried several ways but ended up using Amyth's answer becuase it was the only way that worked.
Here is my admin action that works with fixture magic
def export_survey(modeladmin, request, queryset):
sysout = sys.stdout
survey = queryset[0]
fname = "%s.json" %(survey.slug)
response = HttpResponse(mimetype='application/json')
response['Content-Disposition'] = 'attachment; filename=%s' %(fname)
sys.stdout = response
call_command('custom_dump', 'complete_survey', survey.id)
sys.stdout = sysout
return response
export_survey.short_description = "Exports a single survey as a .json file"
DB fixtures typically compress well, and loaddata can read compressed fixtures. To write a .bz2 compressed fixture directly:
import bz2
with bz2.BZ2File('db.json.bz2', 'w', buffering=1024) as f:
django.core.management.call_command('dumpdata', stdout=f)
This one help for multiple dump data into json file
from django.core.management import call_command
import sys
sys.stdout = open('app_one/fixtures/apple.json', 'w')
call_command('dumpdata', 'app_one.apple')
sys.stdout = open('app_two/fixtures/banana.json', 'w')
call_command('dumpdata', 'app_two.banana')