I am new to Django and have a basic question. I created a Django template, and would like to pass external variables to it, which controls colspan tag. I tried several times, but could not deliver the variable. I appreciate any help.
Python Code:
def getdjtemplate(th_span="1"):
dj_template ="""
<table class="out_">
{# headings #}
<tr>
{% for heading in headings %}
<th colspan={{ %s }}>{{ heading }}</th>
{% endfor %}
</tr>
</table>
"""%(th_span)
return dj_template
I think I should not use this, but not sure how to fix it.
<th colspan={{ %s }}>{{ heading }}</th>
You are just returning a string. You must call the django methods to render the template:
from django.template import Context, Template
def getdjtemplate(th_span="1"):
dj_template ="""
<table class="out_">
{# headings #}
<tr>
{% for heading in headings %}
<th colspan={{ th_span }}>{{ heading }}</th>
{% endfor %}
</tr>
</table>
"""
t = Template(dj_template)
headings = ["Hello"]
c = Context({'headings':headings, 'th_span':th_span})
return t.render(c)
Related
say we have table in template
<table class="table">
<thead>
<tr>
<th>Status</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
{% if {{student.academic_status}}=="promoted" %}
<td class=text-success>promoted</td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
So is it possible using if statement in table in django-templates
Since you are already in a template tag, you should not use curly brackets ({{ … }}) for the variable, so:
{% if student.academic_status == "promoted" %}
…
{% endif %}
The correct way to add if statement in Django Templates
follow me !
if statement
{% if condition %}
{{here you add the key that you using in the views page exactly context}}
{% endif %}
I'm building a fantasy baseball website in python/flask, using Bulma for the css. I'm fairly new to flask development. MySql is the backend database. The page that I'm building is to show draft results. I'm done with the exception of this little pesky problem. I've done lots of searching, but haven't found my specific answer, so asking for a little help...
The page displays a table of draft results. Each row will contain either a major league baseball player or a minor league player, but not both. In other words, one of the last 2 columns should be blank, one should have a player name with a link to his mlb/milb page. What I'm getting is this:
What I want is for the "None" values to be blank. Here is my relevant code:
app.py
#app.route('/draft_results_prior/<string:yr>/')
def draft_results_prior(yr)
try:
conn = mysql.connect()
cursor = conn.cursor(pymysql.cursors.DictCursor)
cursor.execute("SELECT dr.draft_round, dr.pick_no, (SELECT af.city FROM act_franchise as af WHERE af.team_id = dr.original_team_id) orig_team, (SELECT af2.city FROM act_franchise as af2 WHERE af2.team_id = dr.traded_team_id) trade_team, dr.mlb_id, CONCAT('http://m.mlb.com/player/',dr.mlb_id) as Link, (SELECT concat(mlbr.name_first,' ', mlbr.name_last) FROM mlb_rosters as mlbr WHERE mlbr.mlb_id = dr.mlb_id) mlb_name, dr.milb_id, CONCAT('http://www.milb.com/player/index.jsp?sid=milb&player_id=',dr.milb_id) as milb_Link, (SELECT concat(milbr.name_first,' ', milbr.name_last) FROM milb_players as milbr WHERE milbr.milb_id = dr.milb_id) milb_name, dr.intl_id FROM draft_results as dr WHERE dr.ibc_year = %s",(yr))
thisDraft = cursor.fetchall()`
return render_template('draft_results_prior.html', thisDraft=thisDraft, yr=yr)
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
return render_template('draft_results_prior.html', thisDraft=thisDraft)
In draft_results_prior.html, I have this table:
<table class="table table-bordered is-fullwidth is-striped is-hoverable">
<thead>
<tr>
<th class= "yellowones">Round #</th>
<th class= "yellowones">Pick #</th>
<th class= "yellowones">Team</th>
<th class= "yellowones">Traded To</th>
<th class= "yellowones">MLB Pick</th>
<th class= "yellowones">MiLB Pick</th>
</tr>
</thead>
{% for dr in thisDraft %}
<tbody>
<td class= "greenones has-text-left">{{dr.draft_round}}</td>
<td class= "greenones has-text-left">{{dr.pick_no}}</td>
<td class= "greenones has-text-left">{{dr.orig_team}}</td>
<td class= "greenones has-text-left">{{dr.trade_team}}</td>
<td class= "greenones has-text-left">{{dr.mlb_name}}</td>
<td class= "greenones has-text-left">{{dr.milb_name}}</td>
</tbody>
{% endfor %}
</table>
I feel like I need some sort of "if" loop around the last 2 columns to check if the value is null, but I'm unsure of the syntax. Any pointers would be really appreciated!
EDITED BASED ON kungpho's answer below:
If I do this:
<td class= "greenones has-text-left">{{dr.mlb_name}}</td>
{% if dr.milb_name %}
<td class= "greenones has-text-left">{{dr.milb_name}}</td>
{% else %}
{% endif %}
I get this:
That is exactly what I want for the MiLB Pick column. So I tried to do the same to the MLB column, but it combined both columns into one:
{% if dr.mlb_name %}
<td class= "greenones has-text-left">{{dr.mlb_name}}</td>
{% else %}
{% endif %}
{% if dr.milb_name %}
<td class= "greenones has-text-left">{{dr.milb_name}}</td>
{% else %}
{% endif %}
This is what it did:
How can I keep both columns?
EDIT #2- CORRECT answer
Here's the correct answer:
{% if dr.mlb_name %}
<td class= "greenones has-text-left">{{dr.mlb_name}}</td>
{% else %}
<td class= "greenones has-text-left"></td>
{% endif %}
{% if dr.milb_name %}
<td class= "greenones has-text-left">{{dr.milb_name}}</td>
{% else %}
<td class= "greenones has-text-left"></td>
{% endif %}
Yields:
Woohoo!
In your case, yes, it looks like a simple if should do the trick. You'll still want to render the column itself, just not the contents, so your HTML stays valid (browsers will often tolerate it if you don't, but it's still better to keep it as clean as possible).
Example:
<td class="greenones has-text-left">
{% if dr.milb_Link %}
{{ dr.milb_name }}
{% else %}
{% endif %}
</td>
If you were just displaying a value and not an HTML element, Jinja2 has a built-in default filter (true here applies it to falsey values, not just undefined variables):
{{ dr.milb_name|default(' ', true) }}
is there a way to remove the repeated th for each row?
I only want it to show at the top of the table, and not repeat for each row that I import from psql. I've searched and tried several options, but none seem to work for me. I'm using Flask and SQLAlchemy to connect to a postgre table. (the table is called injection)
This is part of my code:
{% block contents %}
<h1>Injection Data</h1>
{% for inject in injection %}
<table>
<tr>
<th>Timestamp</th>
<th>Cage Identifier</th>
<th>Ear Notch Number</th>
<th>Age</th>
<th>Date of Birth</th>
<th>Strain</th>
</tr>
<tr>
<td>{{inject.Timestamp}}</td>
<td>{{inject.Cage_Identifier}}</td>
<td>{{inject.Ear_Notch_Number}}</td>
<td>{{inject.Age}}</td>
<td>{{inject.DOB}}</td>
<td>{{inject.Strain}}</td>
</tr>
</table>
{% endfor %}
{% endblock contents %}
However, the column headers th will repeat for each row of data that is imported from the postgre table.
Your <th> and <table> must not be in loop only <tr><td></td></tr> needs to be in loop,
like below.
{% block contents %}
<h1>Injection Data</h1>
<table>
<tr>
<th>Timestamp</th>
<th>Cage Identifier</th>
<th>Ear Notch Number</th>
<th>Age</th>
<th>Date of Birth</th>
<th>Strain</th>
</tr>
{% for inject in injection %}
<tr>
<td>{{inject.Timestamp}}</td>
<td>{{inject.Cage_Identifier}}</td>
<td>{{inject.Ear_Notch_Number}}</td>
<td>{{inject.Age}}</td>
<td>{{inject.DOB}}</td>
<td>{{inject.Strain}}</td>
</tr>
{% endfor %}
</table>
{% endblock contents %}
I'm working with Flask on building a Bootstrap table out of a list of people taken from a SQLAlchemy database. However, the information I want to put in the table is appearing above it.
Here's the code in question:
<!DOCTYPE html>
{% extends "base.html" %}
{% block page_content %}
<div class="page-header">
<h1>componentes familiares</h1>
<table class="table">
<thead>
<th>name</th>
<th>age</th>
<th>option</th>
</thead>
<tbody>
{% for person in people %}
<tr>{{ person.name }}</tr>
<tr>{{ person.age }}</tr>
<tr>{{ person.option }}</tr>
{% endblock %}
</tbody>
</table>
{% endblock %}
(This is already a slimmed-down version, since I kept taking stuff off to see if it would solve the problem.)
But let's say I have two persons in my database, Alice, and Bob. Alice is 30 and Bob is 40, Alice's option is 1 and Bob's is 2. This is what I get:
The information is there, but it's rendered above the table. And right below it comes the table header and an empty table row.
Links
I found another question about Bootstrap tables in Flask here, but it didn't really solve my problem. My data is being passed to the html page exactly as I want it, I just want to put it in a table.
I also found Flask-Table, an extension to build the table in Python and then using it. It may end up being a solution, but I still don't see what's wrong with my code.
Didn't find anything useful in the Bootstrap docs either.
Any help greatly appreciated!
You're missing a few <tr> and <td> tags:
<table class="table">
<thead>
<tr>
<th>name</th>
<th>age</th>
<th>option</th>
<tr>
</thead>
<tbody>
{% for person in people %}
<tr>
<td>{{ person.name }}</td>
<td>{{ person.age }}</td>
<td>{{ person.option }}</td>
</tr>
{% endfor %}
</tbody>
</table>
You're aiming for a table-row (<tr>) per user, and some table-data (<td>) for each of their attributes. You've also got a {% endblock %} where you should have an {% endfor %}.
I have Django 1.7.1 and Python 2.7.8
I want to get a PDF from a rendered html template, I have tried PISA (xhtml2pdf) but first, i had a lot of problems with Bootstrap css, then, after deleting some lines, this message appeared:
'CSSTerminalFunction' object has no attribute 'lower'
'lower' seems to be part of python 3 and not available in 2.7 (If I am wrong, please tell me)
Now I am trying to use wkhtmltopdf but the documentation is too basic. It describes only one simple example with static HTML
Can someone explain how I can get a PDF with my actual template?
In the template, i have 2 links to css files, and one Image (logo)
I have some bootstrap css style, and i want to use it if possible
I put a "queryset" (actually a tuple) in the template to be rendered inside a table
I also put some string parameters to be rendered in deferent locations in my html.
Here is a part of the template
{% extends 'reporteBase.html' %}
{% block titulo %}Reporte - Inventario por Ubicación{% endblock %}
{% block content %}
{% if productos %}
<h2>Inventario de la ubicación "{{ ubi }}"</h2>
<div class="row" style="margin-top: 2em">
<table class="table table-condensed" data-resizable-columns-id="demo-table">
<thead>
<tr>
<th data-resizable-column-id="mod">Modelo/Item</th>
<th data-resizable-column-id="desc">Descripcion</th>
<th data-resizable-column-id="cant" data-noresize>Cantidad</th>
<th data-resizable-column-id="unidad" data-noresize>Unidad</th>
<th data-resizable-column-id="ubi" data-noresize>Ubicacion</th>
</tr>
</thead>
<tbody>
{% for p in productos %}
<tr>
<td>{{ p.producto__item}}</td>
<td>{{ p.producto__descripcion }}</td>
<td>{{ p.sum_cantidad }}</td>
<td>{{ p.producto__unidad }}</td>
<td>{{ p.ubicacion__nombre }}</td>
</tr>
{% empty %}
<tr><td colspan=4>No hay Productos</td></tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% endblock %}
Thanks!
A view needs to render the template as a PDF. That's what the code from the django-wkhtmltopdf Simple Example does.
Try rendering the page as HTML first to make sure the template is working. You could do this with a view like:
url(r'^html_preview/$',
TemplateView.as_view(template_name='pdf_template.html'))
After you've solved any issues with the template, then try it with PDFTemplateView.