Modify data cell of table with condition in Jinja - python

I have made a page that shows a table with two columns: Users and their Points.
I want to make bold the data cell that has the name of the User session. The table is made in a Jinja for loop. So I created a .bold class in CSS and a condition inside the loop. But it doesn't work at all.
I am very new at code so I am sorry if my question is very simple. Thanks in advance.
I think this is the relevant part of my index.
if request.method == 'GET':
user = session['user_id']
userN = db.execute("SELECT username FROM users WHERE id=?", user)
username = userN[0]["username"]
return render_template('index.html', fixtures=fixtures, username=username, homeScore=homeScore, awayScore=awayScore, userScore=userScore, userHome=userHome, userAway=userAway, usuarios=usuarios)
My HTML:
{% for user in usuarios %}
<tr>
{% if user["username"] == "{{ username }}" %}
<td class="bold">{{ user["username"] }}</td>
{% else %}
<td>{{ user["username"] }}</td>
{% endif %}
<td>{{ user["puntos"] }}</td>
</tr>
{% endfor %}
</tbody>

Thank you all for your answers.
It finally worked!
I followed the advice of RodrigoCava and Maiels and got it. It was an issue with the database query and also I was putting {{ }} where I shouldn't.
This is the final code:
def index():
if request.method == 'GET':
user = session['user_id']
usern = db.execute("SELECT username FROM users WHERE id=?", user)
username = usern[0]["username"]
And the HTML
{% for user in usuarios %}
<tr>
{% if user["username"] == username %}
<td class="bold">{{ user["username"] }}</td>
{% else %}
<td>{{ user["username"] }}</td>
{% endif %}
<td>{{ user["puntos"] }}</td>

Related

Pass information from html form to python flask

I am new to flask and web applications, trying to create a web application that takes the name and the sport for each user and store it in sqlite DB, now Iam trying to remove users from the DB by taking the registrant id from the html to flask.
flask:
#app.route("/deregister")
def deregister():
value_from_html = ?????
db.excute("DELETE * FROM registrant WHERE id = ?", value_from_html)
html:
{% extends "layout.html" %}
{% block body %}
<h1>Registrant name</h1>
<tbody>
{% for registrant in registrants %}
<tr>
<td>{{ registrant.name }}</td>
<td>{{ registrant.sport }}</td>
<td>
<form action="/deregister" method="post">
<input name="id" type="hidden" value="{{ registrant.id }}"> !-- trying to pass registrant.id to flask --!
<input type="submit" value="Deregister">
</form>
</td>
</tr>
{% endfor %}
</tbody>
{% endblock %}
python code is not complete yet.
You can recieve the form data in the following way.
#app.route("/deregister", methods=['POST'])
#login_required
def deregister():
try:
if request.method == 'POST':
if request.files:
uploaded_file = request.files['filename']
data = uploaded_file.stream.read()
In order to send a variable to flask, you dont need to use forms, you can easily do that in the following way,
#app.route("/deregister/<string:id>", methods=['POST'])
#login_required
def deregister(id):
try:
variable = id
print(variable)
In html, keep this,
{% extends "layout.html" %}
{% block body %}
<h1>Registrant name</h1>
<tbody>
{% for registrant in registrants %}
<tr>
<td>{{ registrant.name }}</td>
<td>{{ registrant.sport }}</td>
<td>
<a href='/deregister/{{ registration.id }}'>Send Id</a>
</td>
</tr>
{% endfor %}
</tbody>
{% endblock %}
After trying to solve it my self finaly Ive found a way to do that:
1)Add button in my html to remove from DB:
I hope that this will help any one as it did for me.

I am having errors with CS50 Finance problem in registration process

The error is ":( registering user succeeds" and ":( registration rejects duplicate username"
The detailed error log mentions that there is no table such as 'stock found'
Other registration processes have green ticks.
Can someone please help out with this code?
Here is my registration code in application.py
#app.route("/register", methods=["GET", "POST"])
def register():
"""Register user"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("Oh dear, give us the username!")
# Ensure password was submitted
elif not request.form.get("password"):
return apology("You have to give us password!")
elif not request.form.get("confirmation"):
return apology("You have to confirm your password!")
# Ensure confirm password is correct
elif request.form.get("password") != request.form.get("confirmation"):
return apology("Oops, your passwords don't match up!")
# Insert user and hash of the password into the table
newuser = db.execute("INSERT INTO users (username, hash) VALUES (:username, :hash)",
username=request.form.get("username"),
hash=generate_password_hash(request.form.get("password")))
if not newuser:
return apology("Someone else swiped right on this Username, try a new one!")
# Query database for username
rows = db.execute("SELECT * FROM users WHERE username = :username",
username=request.form.get("username"))
# Remember which user has logged in
session["user_id"] = rows[0]["id"]
# Redirect user to home page
return redirect(url_for("index"))
# User reached route via GET (as by clicking a link or via redirect)
else:
return render_template("register.html")
I have also given below the index code below - for the error with 'stock' table
#app.route("/")
#login_required
def index():
"""Show portfolio of stocks"""
# Query infos from database
rows = db.execute("SELECT * FROM stocks WHERE user_id = :user",
user=session["user_id"])
cash = db.execute("SELECT cash FROM users WHERE id = :user",
user=session["user_id"])[0]['cash']
# pass a list of lists to the template page, template is going to iterate it to extract the data into a table
total = cash
stocks = []
for index, row in enumerate(rows):
stock_info = lookup(row['symbol'])
# create a list with all the info about the stock and append it to a list of every stock owned by the user
stocks.append(list((stock_info['symbol'], stock_info['name'], row['amount'], stock_info['price'], round(stock_info['price'] * row['amount'], 2))))
total += stocks[index][4]
return render_template("index.html", stocks=stocks, cash=round(cash, 2), total=round(total, 2))
HTML for register
{% extends "layout.html" %}
{% block title %}
Register
{% endblock %}
{% block main %}
<form action="/register" method="post">
<fieldset>
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="confirmation" placeholder="Confirm password" type="password">
</div>
<button class="btn btn-primary" type="submit">Register</button>
</fieldset>
</form>
{% endblock %}
HTML for Index
{% extends "layout.html" %}
{% block title %}
Stocks
{% endblock %}
{% block main %}
<table class="table">
<thead class="thead-light">
<tr>
<th scope="col">Symbol</th>
<th scope="col">Name</th>
<th scope="col">Shares</th>
<th scope="col">Price</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
{% for stock in stocks %}
<tr>
<th scope="row">{{ stock[0] }}</th>
<td>{{ stock[1] }}</td>
<td>{{ stock[2] }}</td>
<td>{{ stock[3] }}</td>
<td>{{ stock[4] }}</td>
</tr>
{% endfor %}
<tr>
<th scope="row">Cash</th>
<td></td>
<td></td>
<td></td>
<td>{{ cash }}</td>
</tr>
<tr>
<th scope="row"></th>
<td></td>
<td></td>
<td></td>
<td>{{ total }}</td>
</tr>
</tbody>
</table>
{% endblock %}
Before Insert user and hash of the password into the table, do SELECT on the request.form.get("username"), to see if the username already exists. Then if something is returned, return an error message. I think that should solve the problem.

Django: autonumbering in HTML

Im currently trying to figure out how to autonumber my tables in my html template.
I can't seem to use the id in the database as it is not autoincrementing as it it is user dependant what they see, so the user would see not a correct ordering. Instead of seeing the table numbering go 1. 2. 3. it is 4. 8. 9. for example.
Originally i have tried this, which gave me the wrong outcome as described above:
template.html
{% for item in x%}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.a}}</td>
<td>{{ item.b}}</td>
<td>{{ item.c}}</td>
</tr>
I have tried something with a while loop:
template.html
{% for item in x %}
{% while z<= item %}
{% z=z+1 %}
<tr>
<td>{{ z }}</td>
<td>{{ item.a}}</td>
<td>{{ item.b}}</td>
<td>{{ item.c }}</td>
</tr>
{% endwhile %}
{% endfor %}
For your reference the model that these templates refer to:
models.py
from django.db import models
from django.conf import settings
class x(models.Model):
creation_date = models.DateTimeField(auto_now = True)
a = models.CharField(max_length=50)
b = models.CharField(max_length=50)
c = models.CharField(max_length=50)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
Thanks in advance for your help!
You can use forloop.counter to count the iterations of a loop. Try this:
{% for item in x %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.a}}</td>
<td>{{ item.b}}</td>
<td>{{ item.c}}</td>
</tr>
{% endfor %}
Reference: for template tag - Django Docs

Django PasswordInput is printing object instead of form field

I am trying to create my own authentication system by making use of Django Auth module. The problem is when I print my form in the template, Username and text field is displaying fine but the password field its displaying object something like this <django.forms.widgets.PasswordInput object at 0x00000000039E1710>
Here is my form
class UserLoginForm(forms.Form):
username = forms.CharField(required = True)
password = forms.PasswordInput(render_value = True)
And the template goes here.
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="/portal/login">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
Some one help me on this
-Vikram
change
password = forms.PasswordInput(render_value = True)
to
password = forms.CharField(widget=forms.PasswordInput(render_value = True))
OK, I got the answer: After correcting the form like this its displaying fine
class UserLoginForm(forms.Form):
username = forms.CharField(required = True)
password = forms.CharField(widget=forms.PasswordInput())
Sorry for the spam
-Vikram

Iterating over submitted form fields in Flask?

In Flask 0.8, I know I can access individual form fields using form.fieldname.data, but is there a simple way of iterating over all the form fields? I'm building an email message body, and I'd like to loop over all the fields and create a fieldname/value entry for each, as opposed to manually building it by naming each field and appending.
I suspect that your are using WTForms.
You can iterate over form data:
for fieldname, value in form.data.items():
pass
You can iterate over all form fields:
for field in form:
# these are available to you:
field.name
field.description
field.label.text
field.data
The form object has an iterator defined on it:
{% for field in form %}
<tr>
{% if field.type == "BooleanField" %}
<td></td>
<td>{{ field }} {{ field.label }}</td>
{% else %}
<td>{{ field.label }}</td>
<td>{{ field }}</td>
{% endif %}
</tr>
{% endfor %}
This is from https://wtforms.readthedocs.io/en/2.3.x/fields/#wtforms.fields.Field.type

Categories