how read specific line from csv file in django - 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")

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")

django pandas dataframe download as excel file

I have a Django app that will be placed in a Docker container.
The app prepares data in Dataframe format. I would like to allow the user to download the data to his/her local drive as excel file.
I have used df.to_excel in the past, but this won't work in this case.
Please advise best way to do this.
As of pandas-0.17, you can let Django write to a BytesIO directly, like:
from django.http import HttpResponse
from io import BytesIO
def some_view(request):
with BytesIO() as b:
# Use the StringIO object as the filehandle.
writer = pd.ExcelWriter(b, engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
# Set up the Http response.
filename = 'django_simple.xlsx'
response = HttpResponse(
b.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
You might need to install an Excel writer module (like xlsxwriter, or openpyxl).
I think it can be even simpler and more concise these days. You can just pass the http response directly to the Excel writer. The following works for me:
from django.http import HttpResponse
import pandas as pd
# df = CREATE YOUR OWN DATAFRAME
response = HttpResponse(content_type='application/xlsx')
response['Content-Disposition'] = f'attachment; filename="FILENAME.xlsx"'
with pd.ExcelWriter(response) as writer:
df.to_excel(writer, sheet_name='SHEET NAME')
return response

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.

Attribute Error in Uploading Excel File to Django

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')

Using Pisa to write a pdf to disk

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.