How to pass a function from view.py to html - python

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

Related

How do I get jinja to work on my html web page

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.

Why is my data is not updating in my flask sqlalchemy?

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.

Accessing Value in Dictionary thru Jinja

In the Python file that controls the Jinja template I create a dictionary:
disp_list = {}
for comp in requested_workspace.components:
if comp.show_on_report_list:
disp_list[comp.label] = {}
disp_list[comp.label]['descrip'] = comp.description
In the Jinja template I want to display values from the dictionary:
<table class="table table-hover">
<tbody>
{% for listing in disp_list %}
<tr>
<td>
{{ listing }}
</td>
<td>
{{ listing['descrip'] }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{{ listing }} displays but {{ listing['descrip'] }} won't display. Am I accessing the 2nd value incorrectly?
The Python file controlling the Jinja template was fine. I didn't change it. The Jinja template (HTML file) was where the change was needed.
{% for item_name, values in disp_list.items() %}
<tr>
<td>
{{ item_name }}
</td>
<td>
{{ values['descrip'] }}
</td>
</tr>
{% endfor %}
Using .items() allows me to use tuple explosion and get 2 values out of the dictionary.

how to disable a button which acts as a link django

What is the best way to disable the "deny" button when "approve" button is clicked ? I have {{some}} that stores the value of approve or deny value.
<button>Approve</button>
<button>Deny</button>
html file
{% if some %}
<table id="example" class="display" cellspacing="0" width="100%" border="1.5px">
<tr align="center">
<th> Student ID </th>
<th> Student Name </th>
<th> Start Date </th>
<th> End Date </th>
<th> Action </th>
<th> Status </th>
</tr>
{% for item in query_results %}
<tr align="center">
<td> {{item.studentID}} </td>
<td> {{item.studentName}} </td>
<td> {{item.startDate|date:'d-m-Y'}} </td>
<td> {{item.endDate|date:'d-m-Y'}} </td>
<td><button>Approve</button> <button {% if some == 'approve' %} disabled{% endif %}>Deny</button></td>
<td>
{% if item.status %}
{{item.status}}
{% else %}
Pending
{% endif %}
</td>
</tr>
{% endfor %}
</table>
{% else %}
the {{some}} gets from here
views.py
def superltimesheet(request):
query_results = Timesheet.objects.all()
data={'query_results':query_results, 'some':'some'}
return render(request, 'hrfinance/supervisor_list_timesheet.html', data)
Use an if tag:
<button{% if some == 'deny' %} disabled{% endif %}>Approve</button>
I am not sure about what are you asking, but you can do an if statement like
{% if some == 'approve' %}
<button>Deny</button>
{% else %}
<button>Approve</button>
{% endif %}
or:
{% if some == 'approve' %}
<button>Deny</button>
{% else %}
tell me if that works or I misunderstood

How can I show in django list of records from db

Can anybody help me? I have a list of 60 records from django database in my html file. I want to show that list in table of 6 columns and 10 rows. In html file I used command {% for %} but the list is in one column.
My html file is:
{% for kategoria in kategorie %}
<table>
<tr>
<th> {{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }}) </th>
</tr>
</table>
{% endfor %}
you can try using divisibleby template tag in your template like this to change row after every six entries.
remember {{ forloop.counter }} {# starting index 1 #} and {{ forloop.counter0 }} {# starting index 0 #}
{% for kategoria in kategorie %}
<table>
{% if not forloop.counter0 |divisibleby:"6" %}
<tr>
{% endif %}
<th> {{ kategoria.glowna|linebreaksbr }} ({{ wpisy_kat }}) </th>
{% if forloop.counter|divisibleby:"6" %}
</tr>
{% endif %}
</table>
{% endfor %}
<table>
{% for object in queryset %}
<tr>
<td> object.attr1 </td>
<td> object.attr2 </td>
<td> object.attr3 </td>
<td> object.attr4 </td>
<td> object.attr5 </td>
<td> object.attr6 </td>
</tr>
{% endfor %}
</table>
If you want to have a more pages with 10 items each page, have a look at django's pagination

Categories

Resources