I used wtforms for my input data. Now, When I am calling the edit route, the data I want to edit is showing to my inputs, but when I submitting it, it keeps adding a data not updating the specific data.
routes.py:
#app.route("/edit/<int:expense_id>", methods=['GET', 'POST'])
def edit(expense_id):
form = ExpenseForm()
expense = Expenses.query.get(expense_id)
budget = Budgets.query.filter_by(id=expense.budget_id).first()
posted_expenses = Expenses.query.filter_by(budget_id=budget.id)
form.categories.data = expense.categories
form.cost.data = expense.category_cost
if form.validate_on_submit():
expense.categories = form.categories.data
expense.category_cost = form.cost.data
db.session.commit()
return render_template("expenses.html", budget=budget, form=form, posted_expenses=posted_expenses, expense=expense)
html:
{% for post in posted_expenses %}
<tr>
<td>{{ post.id }}</td>
<td>{{ post.categories }}</td>
<td>{{ "{:,.2f}".format(post.category_cost|float) }}</td>
<td>{{ post.category_date.strftime('%Y-%m-%d') }}</td>
<td>EditDelete</td>
</tr>
{% endfor %}
</tbody>
<form action="{{ url_for('expenses', budget_id=budget.id )}}" method="POST">
{{ form.csrf_token }}
<tbody class="table-input">
<tr>
<td>
{{ form.categories.label }}
</td>
<td>
{{ form.categories }}
</td>
<td>
{{ form.cost.label }}
</td>
<td>
{{ form.cost }}
</td>
<td>
{{ form.submit }}
</td>
</tr>
</tbody>
</form>
I also try to use return redirect in my if but nothing happens.
Related
The table I am trying to fetch data from and put on the html web page is called "Conservative" but none of the data appears on the web page where I have put the jinja variables.
Here is the flask code:
#app.route("/consrecommend")
#login_required
def consrecommend():
"""Show Conservative Recommendations"""
user_id = session["user_id"]
contransactions = db.execute("SELECT name, percentage, investment FROM conservative WHERE
user_id = ?", user_id)
for i in range(len(contransactions)):
contransactions[i]["investment"] = usd(contransactions[i]["investment"])
return render_template("consrecommend.html", contransactions=contransactions)
No data from database "Conservative" shows up on the html web page. Here is the jinja code on web page:
{% extends "layout.html" %}
{% block title %}
Conservative Portfolio Recommendation
{% endblock %}
{% block main %}
<table>
<thead>
<tr>
<th>Name</th>
<th>Percentage</th>
<th>Investment</th>
</tr>
</thead>
<tbody>
{% for contransaction in contransactions %}
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
<tr>
<td> {{ contransaction["name"] }} </td>
<td> {{ contransaction["percentage"] }} </td>
<td> {{ contransaction["investment"] }} </td>
</tr>
{% endfor %}
</tbody>
</table><br><br>
<center><img class="img-scale" src="{{ static('/images/consport.jpg') }}"
alt="Conservative Portfolio" /></center>
{% endblock %}
I hope you're using SQLite3.
In sqlite3, if you are using cur.execute function, it will return sqlite3.Cursor, which is an iterator. And you can directly use for loop with this returned object.
Do remember, since this is an iterator, you will lose all the data once you read it.
So you have to save the data while you are reading. That's why you need to use .fetchall(), which will return the list of queryset.
Note:
If you're using another db like postgres, pscopg2.cursor.execute function won't return anything like sqlite3.Cursor in sqlite, so you can't able to run the loop directly. You should call .fetchall() function.
views.py
def detect_full_text(tweet):
if 'retweeted_status' in tweet.*_json*:
analysis_tweet = tweet._json['retweeted_status']['full_text']
else:
analysis_tweet = tweet.full_text
return (analysis_tweet)
public_tweet.html
{% for analyze in analysis %}
<tr>
<td>
{{ detect_full_text(analyze) }}
</td>
<td>
{{ analyze.created_at }}
</td>
<td>
{{ analyze.favorite_count }}
</td>
<td>
{{ analyze.retweet_count }}
</td>
</tr>
{% endfor %}
I want to call python function from view.py in the html page
I'm trying to include a template inside a for loop with a batch filter applied
But I can't figure out how/if I can include for each object in the list that the filter returns
I see people online selecting from the loop like so:
{% for result in results %}
<tr>
<td>{{ result[0] }}</td>
<td>{{ result[1] }}</td>
<td>{{ result[2] }}</td>
</tr>
{% endfor %}
I just can't figure out how to include for each in the list
My code is as follows:
{% for post in posts | batch(2, ' ') %}
<tr>
<td style="Width: 10%; height: auto">
{% include '_post.html' %}
</td>
</tr>
{% endfor %}
Including portions of a template in a loop/filter construction is perfectly fine.
Using your example, to build a table of posts using a partial template for each batch, you'll need:
The template with the loop/filter where you include the partial:
<table>
<thead><tr>
<th>Title</th>
<th>Author</th>
<th>Title</th>
<th>Author</th>
</tr></thead>
<tbody>
{% for row in posts | batch(2) %}
{% include "row.html" %}
{% endfor %}
</tbody>
</table>
The partial template "row.html":
<tr>
<td>{{ row[0].title }}</td>
<td>{{ row[0].author }}</td>
<td>{{ row[1].title }}</td>
<td>{{ row[1].author }}</td>
</tr>
Another option would be to iterate over the batch partition again and use a simpler partial template:
The template:
<table>
<thead><tr>
<th>Title</th>
<th>Author</th>
<th>Title</th>
<th>Author</th>
</tr></thead>
<tbody>
{% for row in posts | batch(2) %}
<tr>
{% for col in row %}
{% include "col.html" %}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
And "col.html":
<td>{{ col.title }}</td>
<td>{{ col.author }}</td>
If it's not working, double check the variable names, partial names, etc.
I want to pass the following dictionary as context to Django template:
context = {'prices': prices, 'listings_links': listings_links, 'listings_names': listings_names, 'photo_links': photo_links}
The dictionary's values are lists.
In the template I want to display those lists as columns in HTML table. However I am not sure how to further develop the following skeleton table code:
<table>
<tr>
<th>Price</th>
<th>Link</th>
<th>Listing name</th>
<th>Photo link</th>
</tr>
{% for loop start here? %}
<tr>
<td> {{prices[0] }} </td>
<td> {{ listings_links[0] }} </td>
<td> {{ listings_names[0] }} </td>
<td> {{ photo_links[0] }} </td>
</tr>
#next rows go here...
{% endfor %}
</table>
In the view, zip your lists into a single iterable.
items = zip(prices, listings_links, listings_names, photo_links)
context = {'items': item}
Then you can unpack items in the template:
{% for price, listing_link, listing_name, photo_link in items %}
<tr>
<td>{{ prices }}</td>
<td>{{ listing_link }}</td>
<td>{{ listing_name }}</td>
<td>{{ photo_link }}</td>
</tr>
{% endfor %}
I would like to print information about all my users and their groups in a template, like this:
{% for user in users %}
<tr>
<td>(there should be enumerate here - 1,2,3,4 etc...)</td>
<td>{{ user.last_name }}</td>
<td>{{ user.first_name }}</td>
<td>
{% for group in user.groups %}
{{ group }}, </td>
{% endfor %}
</tr>
{% endfor %}
but it doesn't work:
'ManyRelatedManager' object is not iterable
I have two additional questions:
1. How can I easily enumerate users, like this:
<tr>
<td>1</td>
<td>Kowalski</td>
<td>John</td>
...
</tr>
<tr>
<td>2</td>
<td>Smith</td>
<td>John</td>
...
</tr>
...
2. How can I print groups like this:
group1, group2, group3
instead
group1, group2, group3,
(last comma is wrong)
Thank you very much.
you should change
{% for group in user.groups.all %}
{{group}}
The following code should do everything you are asking for:
{% for user in users %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ user.last_name }}</td>
<td>{{ user.first_name }}</td>
<td>
{% for group in user.groups.all %}
{{ group }}
{% if not forloop.last %},{% endif %}
{% endfor %}
</td>
</tr>
{% endfor %}
Check out the following link from the official docs for more information about builtin forloop variables: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for