I'm using Python Pyramid with MongoDB. When I selected multiple images, it will save the image name into session. On the confirmation page, I will retrieve the image name from the session and thus get the image pathname from the database.
this is what I have right now in Views.py
session = request.session
greet_array = session['selectgreetings'].split(",")
greet = GreetingsImg(request)
print("session['selectgreetings']: " , greet_array)
for g in greet_array:
print('g: ' , g)
greetall = greet.get_by_name(g)
for ga in greetall:
greet_path = ga['path_name']
print('path: ', greet_path)
return {'greet_path':greet_path}
if I do this, it will print this results (Command Prompt)
session['selectgreetings']: ['Pics3', 'Pics2']
g: Pics3
path: static/image/greeting/03.jpg
g: Pics2
path: static/image/greeting/02.jpg
I was trying to combine the two paths so that I can get this in Command Prompt:
static/image/greeting/03.jpg, static/image/greeting/02.jpg
When I get the result above, I can use for loop in jinja2 to show the image selected:
{% for a in greet_path %}
<img src="/{{a}}" class="col-sm-5"/>
{% endfor %}
You can combine the contents of an array into a string, with each element separated by a comma, by doing this:
", ".join(greet_path)
Related
I am using django.contrib.humanize intcomma tag to format large numbers like this $18,162,711,641
but what I want spaces instead of comma, like this $18 162 711 641
How can I achieve this? Thank you.
Thanks to Abdul Niyas P M
This is what works for me. I had to put this in app_name/templatetags directory and load it in template using {% load intspace %}
from django import template
register = template.Library()
#register.filter
def intspace(value):
import re
orig = str(value)
new = re.sub(r"^(-?\d+)(\d{3})", r"\g<1> \g<2>", orig)
if orig == new:
return new
else:
return intspace(new)
inside template you can use it like
{{ 18162711641|intspace }}
python function returns a python list
python module function
with open(xml_append_back) as fd1:
doc = xmltodict.parse(fd1.read())
codes = []
for p in doc['Des']['Config']:
codes.append(p['#Id'])
codes.append(pl['#name'])
print(codes)
return codes
codes = ['f2ee4681', 'Conf. no: 1', '89282c5b', 'Conf. no: 2', '3e9dd219', 'Conf. no: 3', '773044b9'] # returned from python to flask template result.html
I call this variable in my templates/flask.html like this
flask file
#app.route('/result',methods = ['POST', 'GET'])
def result():
const_ids=run_d.run_de_selected_configs() # this function returns "codes"
return render_template("result.html",result =
constraint_names_from_form,result1=constraint_ids)
result.html file
{% for key,key1 in result1 %}
<tr class="even"><td>{{ key }}</td><td>{{ key1 }}</td></tr>
should be
<tr class="even"><td>f2ee4681</td><td>Conf. no: 1</td></tr>
{% endfor %}
What am I doing wrong
To answer my own question
I used zip utility in my python code as zip is not available in flask
function returncodes()
-------
---------
return zip(codes,codeNames) # in my case
no change in the flask template
#app.route('/result',methods = ['POST', 'GET'])
def result():
const_ids=run_d.run_de_selected_configs() # this function returns "codes"
return render_template("result.html",result =
constraint_names_from_form,result1=constraint_ids)
now in my result.html
{% for keys,keys2 in result1 %}
<tr class="even"><td>{{keys}}</td><td>{{keys2}}</td></tr>
{% endfor %}
Currently your code is packing all the Id and name values into a single flat list. That doesn't work right when you later need to iterate over it, as you want two values per iteration and you're only getting one.
While there are some ways to iterate over pairs from a list (e.g. zip(*[iter(x)]*2)), I would suggest that you just build a list of tuples directly.
Try changing:
codes.append(planet['#Id'])
codes.append(planet['#name'])
To:
codes.append((planet['#Id'], planet['#name']))
I have this function which is making a request to an api with get. the response is coming back and expected and I am printing out each name of the objects returned to the terminal. But when I use the same for loop to print data in the template only the name of the last object is being rendered on the template page.
I was thinking maybe I am not executing my for loop properly but if that was true then why is my data outputting correctly in terminal.
In my view
def graphs(request):
if request.user.is_authenticated():
data = []
r = requests.get('https://api.deckbrew.com/mtg/cards')
jsonList = r.json()
cardData = {}
for cards in jsonList:
cardData['name'] = cards['name'] # Only last object name
print(cards['name']) # Prints to termainl correct
data.append(cardData)
return render(request, 'graphs/graphs.html', {'data': data})
else:
return redirect('index')
This is in my template # I only get the last objects name
{% for card in data %}
<tr>
<td>{{ card.name }}</td>
</tr>
{% endfor %}
When I move the data.append inside the for loop it appends the same name to the list for each time there is a card in the response.
for cards in jsonList:
cardData['name'] = cards['name']
print(cards['name'])
data.append(cardData)
It's because you declared
cardData = {}
outside your loop and the same instance is being written over and the same dictionary is being pushed onto the array. On the last iteration the entire list has the last name.
Move that declaration inside the loop. Or better still, just append each card onto the list.
Your indentation is wrong too. You only ever put the last instance on the results list. Do this:
for cards in jsonList:
data.append(cards)
You need to initialize the dictionary and call append() inside the loop:
for cards in jsonList:
cardData = {}
cardData['name'] = cards['name']
data.append(cardData)
Or, even shorter (and faster), with a list comprehension:
data = [{'name': cards['name']} for cards in jsonList]
Suppose I have model Abc and Tags which have many to many relation,
options = Abc.objects.all()
tagsset = []
for entry in options:
tags_arr = entry.tags_set.all()
if tags_arr:
tagsset.append(tags_arr)
data = {}
How do I format my queryset both options and tagsset in data?
You can put them in a dictionary, convert them to json, and them return the json_object
data = {}
data['options'] = options
data['tagsset'] = tagsset
json_object = json.dumps(data)
return HttpResponse(json_object)
This above code will send the json object to the calling ajax method
Simple answer:
data = {}
data['options'] = options
data['tagset'] = tagset
# NOTE: since you skip empty tag sets,
# len(tagset) <= len(options)
# so if you are going to match tagsets with options in the
# browser, they may not match length-wise
Although the question asked only about formatting the return parameters, this answer shows a different way to do the same (which is better IMO for cases where there is more data to be packed and sent. This approach also keeps related data together, i.e. options and related tags are binded together.
# payload is the data to be sent to the browser
payload = []
# get all options and associated tags
# this will be a list of tuples, where each tuple will be
# option, list[tags]
for option in Abc.objects.all():
payload.append((
option, # the option
list(option.tags_set.all()), # list of linked tags
))
# return this payload to browser
return HttpResponse(
# good practice to name your data parameters
json.dumps({ 'data': payload, }),
# always set content type -> good practice!
content_type='application/json'
)
# in the browser template, you can do something such as:
{% for option, tags in data %}
{{ option.something }}
{% for tag in tags %}
{{ tag.something }}
{% endfor %}
{% endfor %}
I'm confused about the behaviour of my model. I've got the model built off the mysql database, and it returns the correct count of 89, but I cannot iterate through it for some reason.
My controller is:
#app.route('/calendar/<date>')
def calendar(date):
cur_date = datetime.datetime.today()
cur_date = cur_date + datetime.timedelta(days=int(date))
cur_date = str(cur_date).split(' ')[0]
x = earnings_calendar.query.filter_by(Date=cur_date).all()
print type(x)
for i in x:
print i
return render_template('calendar.html', data=x)
But when I perform:
{% for i in data %}
{{i['Qtr']}}
{% endfor %}
In the view, only one item shows. The length of x is 1, but if I change all to count it shows 89. How do I iterate through to show all 89?
I have not defined a representation, do I need to? I thought it was optional.