How can I feed a server side Django string array into a client side JavaScript array? - django

On my server the array appears as follows:
data = [u'Data1', u'Data2', u'Data3']
In Django, I send the data through to the client using:
render(..., {'data': data})
On the client side I try to render in JavaScript using:
{{data}}
and get:
[u'Data1B', u'Data2', u'Data3']
How can I fix this encoding issue?

You need to safe escape the string inorder to work fine
{{data|safe|escape}}

You can also pass your data as a json object. In your view.py
from django.utils import simplejson
...
render(...{'data':simplejson.dumps(data)})
and then in your javascript function
var data = JSON.parse({{data}})
But as #karthikr already said, |safe is your case absolutely sufficient.

Related

How to send multiplechoicesfield in post request - Postman

I use django-multiselectfield package in my project and based on its docs I use MultipleChoiceField in my serializer:
class InsCatSerializer(serializers.ModelSerializer):
levels = fields.MultipleChoiceField(choices=LEVEL)
when I send a request with raw JSON in postman that works fine
"levels": ["INTERMEDIATE", "ADVANCED"]
But I need to use form data because I have files and images in my request!
I try this way:
levels:INTERMEDIATE
levels:ADVANCED
but just saved the last element ( ADVANCED in this example )
any suggestion to solve?
Json Array and Form data can't work together. Please stringify your array or don't use form data at all.
Read more: JS, how to append array in FormData?

Flask - Generated PDF can be viewed but cannot be downloaded

I recently started learning flask and created a simple webapp which randomly generates kids' math work sheets in PDF based on user input.
The PDF opens automatically in a browser and can be viewed. But when I try downloading it both on a PC and in Chrome iOS, I get error messages (Chrome PC: Failed - Network error / Chrome iOS:the file could not be downloaded at this time).
You can try it out here: kidsmathsheets.com
I suspect it has something to do with the way I'm generating and returning the PDF file. FYI I'm using ReportLab to generate the PDF. My code below (hosted on pythonanywhere):
from reportlab.lib.pagesizes import A4, letter
from reportlab.pdfgen import canvas
from reportlab.platypus import Table
from flask import Flask, render_template, request, Response
import io
from werkzeug import FileWrapper
# Other code to take in input and generate data
filename=io.BytesIO()
if letter_size:
c = canvas.Canvas(filename, pagesize=letter)
else:
c = canvas.Canvas(filename, pagesize=A4)
pdf_all(c, p_set, answer=answers, letter=letter_size)
c.save()
filename.seek(0)
wrapped_file = FileWrapper(filename)
return Response(wrapped_file, mimetype="application/pdf", direct_passthrough=True)
else:
return render_template('index.html')
Any idea what's causing the issue? Help is much appreciated!
Please check whether you are using an ajax POST request for invoking the endpoint to generate your data and display the PDF respectively. If this is the case - quite probably this causes the behaviour our observe. You might want to try invoking the endpoint with a GET request to /my-endpoint/some-hashed-non-reusable-id-of-my-document where some-hashed-non-reusable-id-of-my-documentwill tell the endpoint which document to serve without allowing users to play around with guesstimates about what other documents you might have. You might try it first like:
#app.route('/display-document/<document_id>'):
def display_document(document_id):
document = get_my_document_from_wherever_it_is(document_id)
binary = get_binary_data_from_document(document)
.........
Prepare response here
.......
return send_file(binary, mimetype="application/pdf")
Kind note: a right click and 'print to pdf' will work but this is not the solution we want

How to send JSON data with form data using Flask

I'm making a system to track entries to a sports day event and I can get the data from the form to the Python back-end but I don't know how to get the data for the event entries to the back-end too.
I have a form I've already created using Flask and WTForms and I can submit all the data relating to the user but since they can enter from just a single event all the way up to every event they are able to enter the form will have a variable number of selection fields, I want to pack this data from the selection fields into a JSON string and then have Python process it since that is very easy. My only problem is, how can I get this data into a JSON string then send it in a single request to the back-end with the other data, like first name, last name etc.
Screenshot showing the user interface of the form
from flask import jsonify
#app.route('/selects')
def selects():
selects = ['one', 'two']
return jsonify(selects)
I have the same question and found answer in this tutorial. If you already use WTForm to make the form, the content can be access via methods. This should be straightforward. https://pythonspot.com/category/pro/web/page/2/

How to capture and modify Google Protocol Buffers in a Django view?

Here is a link to the proto file.
Please can someone help me understand how to make this work:
from django.views.decorators.csrf import csrf_exempt
from bitchikun import payments_pb2
#csrf_exempt
def protoresponse(request):
xpo = payments_pb2.Payment.ParseFromString(request)
t = type(xpo)
xpa = request.PaymentACK
xpa.payment = xpo.SerializeToString()
xpa.memo = u'success'
return HttpResponse(xpa.SerializeToString(), content_type="application/octet-stream")
All input appreciated :)
OK so I think I understand what is happening now. You have a system which is POSTing a serialized protobuf to your Django app, and you need to return another protobuf in response.
In Django, you can access the data from a POST in request.body. That is probably what you need to pass to ParseFromString.
You have some other errors too: you refer to request.PaymentACK, which doesn't exist - you mean payments_pb2.PaymentACK - and you never actually instantiate it. Also, you are trying to pass the serialized version of the original request protobuf to that response one, when you should be passing the actual message.
So, altogether it would look like this:
xpo = payments_pb2.Payment.FromString(request.body)
xpa = payments_pb2.PaymentACK()
xpa.payment = xpo
xpa.memo = u'success'
return HttpResponse(xpa.SerializeToString(), content_type="application/octet-stream")

Get value in a post request, Django

am getting the following post data in my django app
POST
Variable Value
csrfmiddlewaretoken u'LHM3nkrrrrrrrrrrrrrrrrrrrrrrrrrdd'
id u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null'
am trying to get the id value in variable id i.e "id":4 (the value 4). When I do request.POST.get('id')I get the whole json string. u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null' How can I get the "id" in the string?
The data you are sending is simply a json string.
You have to parse that string before you can access data within it. For this you can use Python's json module (it should be available if you're using Python 2.7).
import json
data = json.loads( request.POST.get('id') )
id = data["id"]
If you somehow don't have the json module, you can get the simplejson module.
For more details, refer this question : best way to deal with JSON in django
That's happening because id is string, not dict as it should be. Please provide your template and view code to find source of problem.