I have this views function to fetch userid and accountnumber from AWS Dynamodb :
def dsctbl2(request):
dynamodb=boto3.client('dynamodb', region_name='us-west-2')
response = dynamodb.scan(
TableName='User-Account')
filtered = response['Items']
length = len(filtered)
for k in range(length):
accnum = filtered[k]['AccountNum']['S']
uid = filtered[k]['UserId']['S']
f = dict(AccountNum=accnum,userID=uid)
rows = list(f.items())
return render('useradd.html',{'rows': rows})
I have tried almost everything but the rows value is just not getting passed to my template. I even tried passing a simple string value and even that is not getting passed. This is my template table where I wish to display the userid and accountnum.
<div class="mytable">
<table>
<thead>
<tr>
<th>Account #</th>
<th>User Id</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td>{{ row.AccountNum }}</td>
<td>{{ row.UserId }}</td>
</tr>
{% endfor %}
</table>
</div>
When I hit the template , nothing shows up. No values are getting displayed except the table headings. Why is render not passing the context variable (list value)from my views to template ? I have been stuck with for about 6 hours ! Can someone resolve this issue ?
return render(request,'useradd.html',{'rows': rows})
you need to pass request as first parameter,
Related
First of all let me tell you that I'm a beginner at this, I'm on the final project of CS50x. My project consists in a webpage that lets you add some weights into a db table, and then it displays those weights and shows you the weight gain/loss. I'm trying to show the results of a query in a table rendered in html using jinja (and python). RP is the identifier(you search for the rp). The desired output is something like this:
[Desired output]
My python code is the following:
#app.route("/weightquery", methods=["GET", "POST"])
#login_required
def weightquery():
if request.method == "POST":
weights = db.execute("SELECT rp, weight, date FROM weights WHERE rp=:rp AND sex=:sex AND user_id=:user_id ORDER BY date DESC",
rp=request.form.get("rp"), sex=request.form.get("sex"), user_id=session["user_id"])
gains = db.execute("SELECT weight FROM weights WHERE rp=:rp AND sex=:sex AND user_id=:user_id ORDER BY date DESC",
rp=request.form.get("rp"), sex=request.form.get("sex"), user_id=session["user_id"])
animal = request.form.get("rp")
for i in range(len(gains)):
for weight in gains[i]:
if i >= 0 and i < (len(gains)-1):
dif= gains[i][weight] - gains[i + 1][weight]
# Store the dif somewhere I can access.
gains[i].update({'weight': dif})
# Since the dif will always have one item less, I make sure to delete the last item.
gains[i].popitem()
return render_template("weightqueried.html", weights=weights, gains=gains, animal=animal, dif=dif)
else:
return render_template("weightquery.html")
My Html template for weightqueried.html is:
{% block main %}
<div class="container">
<h3>{{ animal }}'s information</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Date</th>
<th>Weight(kg)</th>
<th>Weight dif(kg)</th>
</tr>
</thead>
<tbody>
{% for rp in weights %}
<tr>
<td>{{ rp['date'] }}</td>
<td>{{ rp['weight'] }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
</tfoot>
</div>
{% endblock %}
Any tips and pointers are greatly appreciated since I'm trying to learn and right now my brain is fried!
Maybe it can be simplified if gains was removed entirely. Iterate over weights, do the dif calculation, and add the result to each dictionary. Then in the template, add a <td> element for rp['dif']. If I understand the problem correctly.....
I have a checkbox pagination where user select some of the option after user submit he get redirect to the page where he sees what all item he selected and value of the item , I want to get the sum of the value of item he selected .
<tbody>
{% for booktest in var1 %}
<tr>
<td width="100%">{{ booktest }}</td>
<td>{{ booktest.rate }}</td>
</tr>
{% endfor %}
</ul>
</tbody>
Above is the HTMl code where i get select item and i want to add all value in {{ booktest.rate }}
views.py
def ResultTest(request):
var = request.POST.get('selectedTests')
booktests = BookTest.objects.filter(test__in=var.split(','))
views.py from where i get selected checkbox data.
You can calculate the sum of the rates with the Sum aggregate function [Django-doc]:
from django.db.models import Sum
def result_test(request):
var = request.POST.get('selectedTests')
booktests = BookTest.objects.filter(test__in=var.split(','))
total_rate = booktests.aggregate(total=Sum('rate'))['total'] or 0
# …
I have this method:
def profile(request):
parsedData = []
if request.method == 'POST':
username = request.POST.get('user')
req = requests.get('https://api.github.com/users/' + username + '/repos')
jsonList = []
jsonList=req.json()
userData = {}
for data in jsonList:
userData['html_url'] = data['html_url']
userData['created_at'] = data['created_at']
userData['updated_at'] = data['updated_at']
userData['forks_count'] = data['forks_count']
parsedData.append(userData)
return render(request, 'app/profile.html', {'data': parsedData})
This code looks into an url like this githubtraining
As You can see, the response contains lots of repositories, however, not every github user has more than 1 repo.
Anyways, on my html view I have this:
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped tablesorter">
<thead>
<tr>
<th class="header"> Url <i class="icon-sort"></i></th>
<th class="header"> Created at <i class="icon-sort"></i></th>
<th class="header"> Updated at <i class="icon-sort"></i></th>
<th class="header"> Forks count <i class="icon-sort"></i></th>
</tr>
</thead>
<tbody>
{% for key in data %}
<tr>
<td>{{ key.html_url }}</td>
<td>{{ key.created_at }}</td>
<td>{{ key.updated_at }}</td>
<td>{{ key.forks_count }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
What happens then? Well, right now, if, for instance, I query the githubtraining user to see it's repos, it shows only the last one, on that and every other user, so, what am I doing wrong here? The loop is there, what am I missing?
You append data only after forloop is finished inside your view. You need to append it after each iteration instead:
for data in jsonList:
userData = {}
userData['html_url'] = data['html_url']
userData['created_at'] = data['created_at']
userData['updated_at'] = data['updated_at']
userData['forks_count'] = data['forks_count']
parsedData.append(userData)
With your current code:
userData = {}
for data in jsonList:
userData['html_url'] = data['html_url']
userData['created_at'] = data['created_at']
userData['updated_at'] = data['updated_at']
userData['forks_count'] = data['forks_count']
parsedData.append(userData)
new userData overrides previous one inside for cycle. And when cycle finishing you have only one record in the list.
Here's my problem:
I want to print a table in template which contains every object with every field
Here's my solution:
views.py
def start(request):
all_rows = Person.objects.all()
all_fields_names = Person._meta.get_fields()
content = { 'all_rows': all_rows,
'all_fields_names': all_fields_names }
return render(request, 'start.html', content)
start.html
<table class="table table-striped table-hover table-responsive">
<thead>
{% for names in all_fields_names %}<th>{{ names.name |title }}</th>{% endfor %}
</thead>
<tbody>
{% for row in all_rows %}
<tr>
<td>{{ row.name }}</td>
<td>{{ row.yabadiba }}</td>
<td>{{ row.value1 }}</td>
<td>{{ row.value2 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Everything works perfectly. The problem is, when I don't know exactly how many fields is in the class. Second of all, my solution break the DRY rule. I've tried:
getattr(row, names)
and nested loops, with no success.
Is there any simple solution?
Moreover: How to print such view for every class?
What you need is values_list query in your views, it returns tuples when iterated over. Each tuple contains the value from the respective field or expression passed into the values_list():
all_fields_names = Mileage._meta.get_fields()
value_fields = [f.name for f in all_fields_names]
all_rows = Mileage.objects.values_list(*(value_fields)) #pass fields to value_list
Then you can use nested for loop in your templates:
{% for row in all_rows %}
<tr>{% for value in row %}<td>{{ value }}</td>{% endfor %}</tr>
{% endfor %}
I'm trying to print out some tuples I have stored in a list however I keep getting blank tables. Here is some of my code:
__init__.py:
def view_jobs():
conn = sqlite3.connect(DBNAME)
c = conn.cursor()
c.execute('SELECT * FROM Companies, Job WHERE Companies.cid = Job.cid')
rows = c.fetchall()
conn.commit()
conn.close()
return rows
web_page.py:
#app.route('/Student/Search', methods=['GET', 'POST'])
def studentSearch():
table = []
if request.method == 'POST':
return render_template('studentsearch.html')
else:
table = adb.view_jobs()
print table
return render_template('studentsearch.html', table=table)
studentsearch.html:
<tr>
<th>Company Name</th>
<th>Company E-mail</th>
<th>Internship Position</th>
<th>Internship Description</th>
</tr>
<tr>
{% for row in table %}
<td>{{row.name}}</td>
<td>{{row.email}}</td>
<td>{{row.job_type}}</td>
<td>{{row.job_description}}</td>
{% endfor %}
</tr>
when I print to console I get the appropriate data but when I run this I get a site with no data output. The only other experience I have with this is with Django and that seemed to hold the attribute names in place when I passed the array to the HTML but I probably I was probably using something more sophisticated for my queries... Not sure if there is anything specific with flask that I am missing.
I'm thinking the error lies with how I'm passing table but I'm not sure what the best way to do that is
The problem is here
<tr>
{% for row in table %}
<td>{{row.name}}</td> # You are trying to access a tuple attribute like a dictionary
<td>{{row.email}}</td> # Same here and below
<td>{{row.job_type}}</td>
<td>{{row.job_description}}</td>
{% endfor %}
</tr>
Changes you can do is
Convert query :
c.execute('SELECT name, email, job_type, job_description FROM Companies, Job WHERE Companies.cid = Job.cid')
Then in the studentsearch.html
Change:
<tr>
{% for row in table %}
<td>{{row[0]}}</td>
<td>{{row[1]}}</td>
<td>{{row[2]}}</td>
<td>{{row[3]}}</td>
{% endfor %}
</tr>