Good day,
I'm asking myself, if it's possible to transfer multiple informations as primary-keys inside my template!?
For example, when clicking on a link inside my table...
In this case im transfering the item-id:
<tbody>
{% for item in dataset %}
<tr>
<td>
Item-Name
</td>
</tr>
{% endfor %}
</tobdy>
Now I want to transfer the id and - let's say - the name! Is something like this even possible?
<tbody>
{% for item in dataset %}
<tr>
<td>
Item-Name
</td>
</tr>
{% endfor %}
</tobdy>
And if it's possible, do I have to chage something inside my urls.py? Right now it's looking like this:
path('index/<str:pk>', views.example, name="Example"),
Thanks for all your help and a great day!
Your url should be
{% url 'Examplepage' id=item.id name=item.name %}"
And your path should be
path('index/<str:id>/<str:name>/', views.example, name="Example"),
Related
I have JSON data that I want to publish on a webpage in a table format. I'm stuck to validate dates in the jinja template as few dates are missing and data needs to be published under those dates only for which data is available.
JSON DATA I HAVE:
https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=241301&date=21-05-2021
[PAGE VIEW I WANT][1]
[1]: https://i.stack.imgur.com/OfVnT.png
MY CODE:
<tbody>
{% for center in centers %}
<tr>
<th scope="row">
<address>
{{ center['name'] }} <br>
{{ center['address'] }}
</address>
</th>
{% for date in dates %}
{% if date == center["sessions"][dates.index(date)]["date"] %}
<td>
{{ center["sessions"][dates.index(date)]["available_capacity"] }} <br>
{{ center["sessions"][dates.index(date)]["min_age_limit"] }} <br>
{{ center["sessions"][dates.index(date)]["vaccine"] }} <br>
</td>
{% else %}
<td>None</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
I have got a solution to this problem. I can preformat data in a new python dictionary rather than direct pushing raw JSON data to the Jinja template, but I'm keener to understand if we can apply any other approach.
You should not add much logic into templates.
There are a few reasons for this:
Best practices. Single responsibility principle.
Good design - application logic independent from the view logic.
Prevent illegible, hard to understand and maintain implementation.
Save your future you from a lot of effort
To be able to do something, especially in a language like Python that allows to mix and go very deep and complex (and even ugly) if you want to, does not mean you should.
I am creating a call reports dashboard in django, and I want to output a postgresql Select query in an HTML table for each date of the month like this:
And this is the output that I am receiving. It is just giving me totals for each extension for the month in each table instead of the total for that distinct date. I tried to change the query to
For whatever reason I am having a very hard time figuring this out. This is my HTML, I know I am not doing the looping right here, I've just been running out of ideas.
{% for i in lt.itertuples %}
<table class="table" style="float:left">
<caption>{{ i.to_date }}</caption>
<thead>
<tr>
<th>Extension</th>
<th>Calls</th>
</tr>
</thead>
{% for d in df4.itertuples %}
<tr>
<td>
{{ d.member_extension }}
</td>
<td>
{{ d.count }}
</td>
</tr>
{% endfor %}
</table>
{% endfor %}
</div>
And this is a snippet of my Python:
query=pd.read_sql_query("select DISTINCT date(start_date) as 'DATE()' from Reports3; ",con3)
query2=pd.read_sql_query("SELECT COUNT(*),member_extension from Reports3 group by member_extension ",con3)
df4 = pd.DataFrame(query)
lt = pd.DataFrame(query2)
ext4=pd.unique(df4['member_extension'])
context={'df4':df4, 'ex4':ext4, 'lt':lt }
return render(request,'index2.html',context)
I tried changing the Query to:
SELECT DISTINCT TO_DATE(start_date,'YYYY-MM-DD'), COUNT(*),member_extension from Reports3 group by member_extension,TO_DATE(start_date,'YYYY-MM-DD') ORDER BY TO_DATE(start_date,'YYYY-MM-DD')
And that outputs this result:
I am using Python FLask to build a webapp and I am trying to push a nested list to a table in HTML.
Python
item = [[22-03-20, $1409.50, 22-03-20], [22-03-20, $60.00, 22-03-20]]
current HTML
{% for rows in item %}
<tr>
<th scope="row">•</th>
{% for cell in rows %}
<td>{{cell}}</td>
{% endfor %}
<td>edit</td>
</tr>
{% endfor %}
The reason for a duplicate of dates in the nested list is because I need to create a special route page to the date itself.
Output I want to achieve
Basically, the edit will redirect to the page to the respective date. As I have multiple expenses of the same date, I can't just use the unique id within the table.
PROBLEM
The current HTML I have is able to output the 3 items I need, date, expense, date but I can't put a URL redirect to the 3rd variable, date. Is there a way to have 2 for loops running parallel to each other, so I could go through 2 lists at the same time? or is there a better way to do what I want to achieve?
Found a way looking through the documentation again, don't need a parallel for loop actually. I changed the nested list to a tuple in a list. Not sure if this is the best way to do it though.
Python
item = [(22-03-20, $1409.50, 22-03-20), (22-03-20, $60.00, 22-03-20)]
HTML
{% for x,y,z in item %}
<tr>
<th scope="row">•</th>
<td>{{x}}</td>
<td>{{y}}</td>
<td>edit</td>
</tr>
{% endfor %}
I think you should use a list of maps.
item = [
{
'date':'22-03-20',
'price':'$1409.50',
'href':'URI'
},
{
'date':'22-03-20',
'price':'$60.00',
'href':'URI'
},
]
so,
{% for row in item %}
<tr>
<th scope="row">•</th>
<td>{{row.date}}</td>
<td>{{row.price}}</td>
<td>
edit
</td>
</tr>
{% endfor %}
Goal: {% for loop %} over a list (using Jinja2) and then print out results {{print}} in a HTML table using Bootstrap.
Problem: List is not printing in the template.
In the view_config, I used query .all() to return a list of all the assessment_results objects. They are returning... I confirmed this via terminal/print debugging. However, the for loop is not returning the values needed to populate a table; as read in Jinja2 tutorial. I don't think I need to use a for loop in the view_config as I have seen others do (see here), but I am new to this and am trying to figure out how these two programs (SQLALCHEMY and Jinja2) interact.
An example from the printout after using .all() mentioned above:
[<Assessment_Result(owner='<User(username ='baseball', firstname ='Jen', lastname ='See', email='girl#aol.com')>', assessment='<Assessment(name='Becoming a Leader', text='better decisions')>')>]
view_config code:
views.py
#view_config(route_name='assessment_results', request_method='GET', renderer='templates/assessment_results.jinja2')
def all_assessment_results(request):
with transaction.manager: # < --- THIS WAS THE ISSUE !
assessment_results = api.retrieve_assessment_results()
if not assessment_results:
raise HTTPNotFound()
return {'assessment_results': assessment_results}
Corresponding Jinja2 template using Bootstrap:
assessment_results.jinja2
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<td> Assessment ID </td>
<td> Assessment </td>
<td> Owner </td>
</tr>
</thead>
<tbody>
<tr>
{% for x in assessment_results %}
<td>{{ x.assessments|e }}</td>
<td>{{ x.owners|e}}</td>
{% else %}
<td><em>no users found</em></td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
You should look at the documentation
http://jinja.pocoo.org/docs/dev/templates/#for
You want to iterate over a dict, so consider using iteritems, itervalues or what ever you want.
Also note that your query will not return a dict, it will return a list or rows that matched.
I am also not sure if the for-else works in jinja. But you should avoid using that anyways.
My issue is that I can't seem to translate the dictionary into a table here's the error:
Could not parse ["appid"] from 'game[''appid"]
HTML code:
<table>
<tr>
<th>Game ID</th>
<th>Game Name</th>
<th>Hours Played</th>
</tr>
{% for game in games %}
{# each game object is a dictionary with "appid", "name " and "playtime_forever" keys #}
<tr>
<td>{{ game["appid"] }}</td>
<td>{{game["name"]}}</td>
<td>{{ game["playtime_forever"] }}</td>
</tr>
</table>
views.py code:
~~~~ There's stuff here but it shouldn't be important. ~~~~
return render(request,'hackathon/SteamAPI.html', game)
When I run the server it shows:
game:
[{u'appid': 4000,
u'has_community_visible_stats': True,
u'img_icon_url': u'd9101cbeddcc4ff06c7fa1936c3f381b0bbf2e92',
u'img_logo_url': u'dca12980667e32ab072d79f5dbe91884056a03a2',
u'name': u"Garry's Mod",
u'playtime_forever': 0},
Django templates do not support [] indexing. Instead of
game["appid"]
you should use
game.appid
The same applies for game.name and game.playtime_forever
As an unrelated note, you should also close your for loop:
</tr>
{% endfor %}
</table>
Dictionary should be accessed this way in Django Templates.
choices = {'key1':'val1', 'key2':'val2'}
<ul>
{% for key, value in choices.items %}
<li>{{key}} - {{value}}</li>
{% endfor %}
</ul>