Cant display the csv data in a seperate file in django - django

I am trying to display some csv(comma seperated values) in my project. So I have a html button click upon which a django view function is called through JavaScript. This is my django view function :
def make_csv(request):
testdata = "[{\"severity\":\"0\",\"description\":\"USB Connected\",\"date\":\"01/01/2015\",\"time\":\"11:35:20\"},{\"severity\":\"3\",\"description\":\"USB Disconnected\",\"date\":\"01/01/2015\",\"time\":\"10:30:19\"}]";
data = json.loads(testdata)
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="eventlog.csv"'
writer = csv.writer(response,csv.excel)
writer.writerow(data[0].keys())
for row in data:
writer.writerow(row.values())
return response
But I can't get any file displayed in my browser. Also I can see the values returned using my JavaScript. Is there a way to display the result as a seperate file in the browser so that users can download it?

Related

In django, how can i upload file via url?

Hi i'm making my own webserver using django.
i just want to upload local file to django server.
i google every method but i can't get answer.
every method using form or html but i don't want to using form and html
example : from www.localfolder/example.txt to /media/examplefolder.
i don't know how to do.. any help?
this is my code.
#csrf_exempt
def download_file(request, file):
fl_path = 'media/'
filename = str(file)
fl = open(fl_path, 'r')
mime_type, _ = mimetypes.guess_type(fl_path)
response = HttpResponse(fl, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename = %s" % filename
return response
What did you search for when you googled? These were the top 2 results for Django files
https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/
https://docs.djangoproject.com/en/3.0/topics/files/
Seems to have everything you are looking for.

Django render to pdf with button

I have def that render to pdf with action on django-admin.
def Print(self, request, obj):
data = {
'obj':obj
}
pdf = render_to_pdf('daa/imprimir/pdf.html', data)
if pdf :
response = HttpResponse(pdf, content_type='application/pdf')
filename ="Avaria_%s.pdf" %("123451231")
content = "inline; filename='%s'" %(filename)
response['Content-Disposition'] = content
download = request.GET.get("download")
if download:
content = "attachment; filename='%s'" %(filename)
response['Content-Disposition'] = content
return response
return HttpResponse("Not found")
and on my actions I have:
class ModelAdmin(admin.ModelAdmin):
actions = [Print]
and it is working all good, I select what objects I want to render and in my html I have cicles that make a list of all fields I want of those obj's.
But right now I don't want to render to pdf a list. I want to render only 1 obj. So I create a custom button to do that.
http://prntscr.com/muijhl
So when I click on button I want to render to pdf the obj which is open. I don't know what I need to do to take my def and but inside of button
For how to hook this code as a view with it's own url, there's a perfect example in the official doc (but you have to know what to look for to find it)
Then you'll have to override your change_form template to add the button/link pointing to this url.

error serving pdf in django 1.8

In django 1.8 I have a couple of functions that read pdf files and return them, and that generate a pdf with reportlab and return it.
In some cases the file is served correctly, but sometimes the PDF is opened by the browser as if it were html and what is even more strange, pdf source is displayed in my django base template.
In this case, if reloading the page after the error, the pdf is served.
This is the code of a view:
fpdf = open (path, 'rb')
return HttpResponse (FileWrapper (fpdf), content_type = 'application/pdf')
and this is the code of the other:
pdf = pisa.CreatePDF (StringIO.StringIO (html.encode ("UTF-8")), result)
if not pdf.err:
response = HttpResponse (result.getvalue (), content_type = 'application / pdf')
response ['Content-Disposition'] = 'attachment; filename =% S.pdf '% (doc.name.replace ("", "_"))
return response
#Return HttpResponse (result.getvalue (), content_type = 'application/pdf')
Returning the PDF as an attachment is a test that I made to see if solved, because the desired behavior would be directly open the file.
Unfortunately, the error still occurs even so.
Change this line
response = HttpResponse (result.getvalue (), content_type = 'application / pdf')
To this line
response = HttpResponse (result.getvalue (), content_type = 'application/octet-stream')
This will make the file to be treated as a binary, and downloaded to the user instead of opening it in the browser.
If you view it inside the browser, follow Igor Pomaranskiy advice, and remove the space inside your content_type variable by doing the following
Change this
content_type = 'application / pdf'
to this
content_type = 'application/pdf'

How to download data in a blob field from database in django?

I have a table in which I have a blob column containing some data, how can i download the blob content in django?
I tried the solution mentioned here but it didn't work for me
def download_blob(request, id):
contents = BlobModel.objects.get(id=id).blob_field
response = HttpResponse(contents)
response['Content-Disposition'] = 'attachment; filename=blob.bin'
return response

Django FileField encoding

I have a django model as follows:
class ExportFile(BaseExportFile):
created_timestamp = models.DateTimeField(auto_now=True, editable=False)
data = models.FileField(upload_to='exports')
and a view function that renders a template to create a csv file:
def create_csv(request):
context = Context({'data': MyModel.objects.all()})
rendered = render_to_string('mytemplate.html', context)
# create tradefile and save
cf = ContentFile(rendered)
tf = ExportFile()
tf.data.save('myfile.csv', cf)
tf.save()
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % 'myfile.csv'
response.write(rendered)
return response
The view not only saves the csv data to a FileField but it also returns it to the browser. The problem I have is the browser file works perfectly, but the file saved on the model is twice the size and when I use a diff program I can see extra hidden characters. I think it must be to do with the mime type vs django auto saving utf8 but I just can't figure it out!
Solved the problem!
The ContentFile is a subclass of cStringIO.StringIO - which deals with ASCII encoded files. The string therefore needs to be encoded as ASCII as everything in django is UTF8 by default
cf = ContentFile(rendered.encode('ascii'))