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.
Related
I am using Django with python to create a web application, I am a beginner in this. I hope that you can help me.
I want to print this page by clicking a button.
Now, I am just trying to generate the pdf first.
I want just to print the content, like that
I tried these functions.
#views.py
from django.views.generic.detail import DetailView
from MagasinProject.views import PdfMixin
from MagasinProject.utils import generate_pdf, render_to_pdf_response, pdf_decorator
from django.contrib.auth.models import User
from django.shortcuts import render
def test_view(request):
resp = HttpResponse(content_type='application/pdf')
result = generate_pdf('demande/demande.html', file_object=resp)
return result
#urls.py
from django.urls import path
from . import views
from django.conf.urls import url
urlpatterns=[
path('demande',views.index, name='demande'),
url(r'^test_view$', views.test_view),
]
This is what I got
You can print the HTML page with a print button like this (see w3schools):
<button onclick="window.print()">Print this page</button>
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()
I am having trouble uploading excel file to my django application. It is a very simple application that should allow a user to upload an excel file with 3 columns. The application will read the contents of this file and process it into bunch of calculations
here is my forms.py:
class InputForm(forms.Form):
FileLocation = forms.FileField(label='Import Data',required=True,widget=forms.FileInput(attrs={'accept': ".xlsx"}))
settings.py:
FILE_UPLOAD_HANDLERS = ["django_excel.ExcelMemoryFileUploadHandler",
"django_excel.TemporaryExcelFileUploadHandler"]
views.py:
import xlrd
from django.shortcuts import render_to_response, render
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.template.context_processors import csrf
from io import TextIOWrapper
from WebApp.forms import *
from django.core.mail import send_mail
from django.utils.safestring import mark_safe
from django.db import connection
import os
import csv
def analyze(request):
if request.method == 'POST':
form = InputForm(request.POST,request.FILES['FileLocation'])
if form.is_valid():
book = xlrd.open_workbook(request.FILES('FileLocation'))
for sheet in book.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
print(number_of_rows)
I upload the file in the form and it gives me an error:
AttributeError at /app/analyze/
'ExcelInMemoryUploadedFile' object has no attribute 'get'
Request Method: POST
Request URL: http://127.0.0.1:8000/data/analyze/
Django Version: 1.11
Exception Type: AttributeError
Exception Value:
Exception Location: C:\Python36\lib\site-packages\django\forms\widgets.py in value_from_datadict, line 367
Python Executable: C:\Python36\python.exe
Python Version: 3.6.4
I am also able to upload a .csv file successfully using the following views.py code:
def analyze(request):
c={}
context = RequestContext(request)
c.update(csrf(request))
abc=['a','b','c']
if request.method == 'POST':
form = InputForm(request.POST,request.FILES)
dataType = request.POST.get("DataType")
print(dataType)
if form.is_valid():
cd = form.cleaned_data #print (cd)
a = TextIOWrapper(request.FILES['FileLocation'].file,encoding='ascii',errors='replace')
#print (request.FILES.keys())
data = csv.reader(a)
row1csv = next(data)
region = row1csv[0]
metric = row1csv[2]
I have tried django-excel with same error.
You're correctly initialising your form for the .CSV case but not in your Excel case:
form = InputForm(request.POST, request.FILES)
Don't initialise using request.FILES['FileLocation'] as that's passing the wrong type to the form. It's expecting a MultiValueDict of uploaded files, not a single uploaded file. That's why it fails when calling get on it.
Next, you can't pass an ExcelInMemoryUploadedFile to xlrd.get_workbook(). You need to save the file to disk first, then pass it's path to the get_workbook() method. The documentation of django-excel gives some easier methods:
book = request.FILES['FileLocation'].get_book() # note the square brackets!
or to directly access a sheet:
sheet = request.FILES['FileLocation'].get_sheet('sheet1')
I have created a webscraper in Python and now I want to insert this file into my views.py and execute them using the HTML button created on the HTML page.
My scraper name is maharera.py and it is saved in same folder where I have saved views.py
My views.py looks like this:
from django.shortcuts import render
from django.conf.urls import url
from django.conf.urls import include
from django.http import HttpResponse
# Create your views here.
def index(request):
first = {"here":"will enter more details"}
return render(request, "files/first-page.html", context=first)
#return HttpResponse("<em>Rera details will be patched here</em>")
After inserting it in views.y I want to execute that file using html HTML I created. How can I do that?
Actual answer to question
Lets say the contents of maharera.py are as follows
def scraper(*args, **kwargs):
#the scraper code goes here
then you'll need to import it as follows in the views.py file
from django.shortcuts import render
from django.conf.urls import url
from django.conf.urls import include
from django.http import HttpResponse
# Create your views here.
import maharera
def index(request):
first = {"here":"will enter more details"}
return render(request, "files/first-page.html", context=first)
#return HttpResponse("<em>Rera details will be patched here</em>")
def scraper_view(request):
maharera.scraper()
return HttpResponse("<em>Scraper started</em>")
It is advisable to not run a web scraper through a http requests like these. Http requests are supposed to return response within fraction of seconds and should not take long.
When you hit scraper_view it will start executing the code inside it. In scraper view, there is call to the scraper and we don't know how long will it take for that function to end. Till that function doesn't end, the response of the page will not be returned to the user.
For such long running tasks, you should look into task queues.
Looking into celery
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.