I'm working with Python/Pyramid and Mako Templates, and it's all pretty new for me.
I have a list over different templates, now the list comes out in a random order but I want it alphabetically.
Does anyone have any suggestions?
Here is the code that gets the list:
<div class="panel-small">
<h2>Choose template</h2>
<div id="template_list">
% if template_list and len(template_list) > 0:
% for template in template_list:
% if template['template']:
<a href="#${template['type']}_${template['template_id']}" id="${template['template_id']}" class="template_link ${template['type']}">${template['name']}<br />
% else:
% if template['url'] is not None and template['url'].startswith('mailto'):
${template['name']}<br />
% else:
${template['name']}<br />
% endif
% endif
% endfor
% else:
No template.
% endif
</div>
</div>
Just sort your "template_list" in python before it gets rendered in the template.
Related
My code is a hybrid (swamp) of snippets from Django documentation, online tutorials and stackexchange answers.
I have a model that contains x and y coordinates of points. One of the x or y coordinates will be +/- 1. The other coordinate will be a real value between -1 and +1. The "other" coordinate values may not be unique. For example, the following are valid coordinates : (0.7,1) , (1, -1), (-1,-0.45) , (0.7, -1), whereas the following are invalid: (0.2,0.3), (3, -1), (1,3).
I have been able to “extract” the coordinates into 4 separate lists when x= +/- 1 or y = +/- 1 so that I can work out the mean of the “other” coordinate. For example, if my filtered list for x = -1 is: [[-1,0.4],[-1,-0.37],[-1,0.78]], I can get the mean of: 0.4, -0.37 and 0.78. In other words, I’m try to get the mean of the values in a particular column in a Python array, where the data has been extracted from a Django model.
I have code in my view that works, but is fantastically complex, and my gut tells me there is probably a sleeker, more efficient and easier to understand solution than the one I have cobbled together. My code is:
#models.py
class CC_pts_to_avg(models.Model):
x_coord = models.DecimalField(max_digits=3, decimal_places=2)
y_coord = models.DecimalField(max_digits=3, decimal_places=2)
#
def __str__(self):
return self.x_coord # Get a better name than this?
#urls.py
from .models import …. CC_pts_to_avg
#views.py
def x_pos1(var_in):
if var_in[0] == 1:
return True
else:
return False
#
def x_neg1(var_in):
if var_in[0] == -1:
return True
else:
return False
#
def y_pos1(var_in):
if var_in[1] == 1:
return True
else:
return False
#
def y_neg1(var_in):
if var_in[1] == -1:
return True
else:
return False
#
from statistics import mean
import numpy as np
def p2points_avg_calc(request):
pollsx3 = CC_pts_to_avg.objects.all() # extract all fields from dbase table to Queryset
list_x_y_coords = list(CC_pts_to_avg.objects.values_list('x_coord','y_coord'))
xpos1_list = np.array(list(filter(x_pos1,list_x_y_coords)))
xneg1_list = np.array(list(filter(x_neg1,list_x_y_coords)))
ypos1_list = np.array(list(filter(y_pos1,list_x_y_coords)))
yneg1_list = np.array(list(filter(y_neg1,list_x_y_coords)))
mean_of_y_for_x_neg1 = mean(xneg1_list[:,1])
mean_of_x_for_x_neg1 = -1
mean_of_y_for_x_pos1 = mean(xpos1_list[:,1])
mean_of_x_for_x_pos1 = 1
context = {
'polls36' : pollsx3, # this is just to display all the data below the template
'mean_of_x_for_x_neg1' : mean_of_x_for_x_neg1,
'mean_of_y_for_x_neg1' : mean_of_y_for_x_neg1
}
return render(request, 'pollapp2/p2pt_avg_calc.html', context) # second parameter is location of HTML source
#p2pt_avg_calc.html template
The following displays the correct values for mean_of_x_for_x_neg1 and mean_of_y_for_x_neg1 passed from the view : p2points_avg_calc (see above)
<!-- p2pt_avg_calc.html -->
{% extends "pollapp2/base.html" %}
<!-- block Title is the name in the tab -->
{% block title %}Average from all points along edge{% endblock %}
{% block main %}
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">The points</h3>
</div>
<strong>x mean:</strong> {{ mean_of_x_for_x_neg1}} <strong>y mean:</strong> {{ mean_of_y_for_x_neg1}}
<ul class="list-group">
{% for pollabcxz in polls36 %}
<li class="list-group-item">
<strong>x:</strong> {{ pollabcxz.x_coord}} <strong>y:</strong> {{ pollabcxz.y_coord}}
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endblock %}
Can you help me make some improvements to my code to make it more efficient, but more importantly more readable, understandable and maintainable should I need to modify it later ?
I want to create a website where the user is asked to type a given number to get the square number and the square root.
This is from index.html:
<div class="d-flex typeW">
<form action="add">
Enter a number : <input type="text" name="num1">
<input type="submit">
</form>
</div>
This is from the result page (where you can see the result):
<div class="d-flex title2">
<h2>
{% block content %}
{{result}}
{% endblock %}
<br><br>
This is from view:
def add(request):
num1 = int(request.GET["num1"])
return render(request, 'result.html' , {result2: num1 * num1})
Now I want to take the square root of that number but I'm not sure how.
How do I take one input and then do two calculations by using two functions?
help much appreciated
Simply do two calculations in your view and return both results within the context. You can then access all values in the context and render them in the template.
import math
def add(request):
# Get the user input
num1 = int(request.GET["num1"])
# Calculate square
num1_square = num1 ** 2
# Calculate root
num1_root = math.sqrt(num1)
# return context
context = {
'square': num1_square,
'root': num1_root
}
return render(request, 'result.html' , context)
# template
<div class="d-flex title2">
<h2>
{% block content %}
{{ square }}
{{ root }}
{% endblock %}
<br><br>
I'm extremely new to python/flask, so I don't have the capacity to describe what I'm doing wrong. Please be patient with me.
As I'm in the learning stages, my goal is to create a simple app with GET, PUT, POST, DELETE functionalities. I'm using flask to render a template for a project; I'm using forms to make an HTML page. The one key issue here is:
in my routes.py
#app.route("/")
#app.route("/home")
def home():
all_pokemon = Pokémon.query.all()
result = ""
for pokemon in all_pokemon:
result += f"{pokemon.id} | {pokemon.pkname} | {pokemon.nickname}<br>"
return result
This, gives me what I want, which is this:
However, I have an home.html setup to do exactly the same thing. Simply show me this information.
in my home.html
{% extends 'layout.html' %}
{% block body %}
<h1>version 1.0.0</h1>
<br>
{% for pokemon in all_pokemon %}
{{ "{pokemon.id} | {pokemon.pkname} | {pokemon.nickname}" }}
<br>
{% endfor %}
{% endblock body %}
and to get that working, i have this in my routes.py
#app.route("/")
#app.route("/home")
def home():
all_pokemon = Pokémon.query.all()
return render_template("home.html", all_pokemon=all_pokemon)
But, doing this, gives me this output:
My question is, how do I get the render_template to NOT display the incorrect output, and to properly display the correct output of my forms?
I've been searching for an answer for this issue without an understanding of the proper terminology and have consequently made no progress for the past 3.5 hours. Any help is greatly appreciated. Swift help is incredibly appreciated.
Thank you. If I need to post more information please let me know.
I've figured it out, and as I suspected it was embarassingly simple.
The render template worked, but where I had
in my home.html
{{ "{pokemon.id} | {pokemon.pkname} | {pokemon.nickname}" }}
I should have had
{{ pokemon.id }} | {{ pokemon.pkname }} | {{ pokemon.nickname }}
I apologise for anybody who may have wasted their time searching for an answer, and I hope this can serve as a helpful guide to any other newbies like myself who get stuck on this.
Hopefully 7 years from now I can look back on this moment affectionately and laugh about it.
{% for pokemon in all_pokemon %}
{{ "{pokemon.id} | {pokemon.pkname} | {pokemon.nickname}" }}
<br>
{% endfor %}
Firstly you should use your context like that:
{{pokemon.id}} | {{pokemon.pkname}} | {{pokemon.nickname}}
And if you want to render your context, your view should be like that:
#app.route("/home")
def home():
all_pokemon = Pokémon.query.all()
result = ""
for pokemon in all_pokemon:
result += f"{pokemon.id} | {pokemon.pkname} | {pokemon.nickname}<br>"
if all_pokemon is not None:
return render_template("home.html", all_pokemon=all_pokemon, result=result)
else:
return render_template("home.html",all_pokemon=all_pokemon, result = "")
If you use your context named result, you should use a control in your template folder like that:
.html
{% if result|length > 1 %}
...
{% endif %}
Im working on the comment section of my page and found a useful website with this https://blog.miguelgrinberg.com/post/implementing-user-comments-with-sqlalchemy. The problem i am having is representing the comments on the website. How to i display nested comments in the same manner as shown in the link above using the flask code below.
for comment in Comment.query.order_by(Comment.path):
print('{}{}: {}'.format(' ' * comment.level(), comment.author, comment.text))
In other words: how would the above segment look as jinja code.
{% for comment in comments %]
.
.
.
{% endfor %}
If there is another way to do it, i'm all ears. Thanks.
Here i am after some research and successful completion of my comment section to answer my own question. To get this effect do this below
{% for comment in all_comments %}
<div class="row">
{% if comment.comment_level == 0 %}
<div class="col-lg-12 ">
{% elif comment.comment_level == 1 %}
<div class="col-lg-1 "></div>
<div class="col-lg-11">
{% elif comment.comment_level == 2 %}
<div class="col-lg-2 c"></div>
<div class="col-lg-10 ">
{% elif comment.comment_level == 3 %}
<div class="col-lg-3 "></div>
<div class="col-lg-9 ">
{% else %}
<div class="col-lg-4 "></div>
<div class="col-lg-8 ">
{% endif %}
<div>
<p>{{comment.text}}</p>
</div>
This will create the step ladder effect you see in comment section. This is a flask solution. I'm sure you can replicate it in other languages.
I am using ExpressionEngine 2.10.3 and also Taxonomy 3 plugin. I have the following code which, when run, returns the 15 nodes I have set up:
<div class="col-md-4">
{exp:taxonomy:nav tree_id="1" display_root="no" root_node_id="2"}
<li>
{node_title}
</li>
{/exp:taxonomy:nav}
</div>
What I would like to do is after every 5 entries, end the current <div> and start a new col-md-4. Usually, I would use {switch} and I have tried it like this:
<div class="col-md-4">
{exp:taxonomy:nav tree_id="1" display_root="no" root_node_id="2"}
<li>
{node_title}
</li>
{switch='||||</div><div class="col-md-4">'}
{/exp:taxonomy:nav}
</div>
But it doesn't work at all, instead it just prints out {switch='||||'}
Is there any way of doing what I'm trying to do?
If you're on 2.7.1 or greater and your taxonomy:nav has the nav_count variable, use the modulo operator. Instead of your {switch...} thing, put
{if nav_count % 5 == 1}
</div><div class="col-md-4">
{/if}
If you end on an modulo-5 count, though, you're going to have an empty div....