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.
Related
I've seen a few CS50 Finance help questions regarding /index. I'm trying to get the route to display a user's owned stock information (share number, value, price, etc.). Right now it displays the correct share amounts but does not display the name, value, or price (all blank). The "cash" and "grandTotal" amounts display but grandTotal is not the correct amount. I think I'm just confused on how to access specific values in my returns.
Python/sqlite:
def index():
"""Show portfolio of stocks"""
# sql queries to select stock info
user_id = session["user_id"]
stocks = db.execute("SELECT stock, symbol, SUM(shares) AS totalShares FROM purchases WHERE userid == :userid GROUP BY symbol", userid=user_id)
currentCash = db.execute("SELECT cash FROM users WHERE id == :userid", userid=user_id)
# Global variables to be updated
tableInfo = []
grandTotal = currentCash[0]["cash"]
#Grabbing info from each owned stock
for stockInfo in stocks:
symbol = stocks[0]["symbol"]
shares = stocks[0]["totalShares"]
name = stocks[0]["stock"]
currentStock = lookup(symbol)
price = currentStock["price"]
value = price * shares
grandTotal += value
tableInfo.append(stockInfo)
# Display a table with portfolio info for current user
return render_template("index.html", tableInfo=tableInfo, grandTotal=usd(grandTotal), currentCash=usd(currentCash[0]["cash"]))
HTML:
{% extends "layout.html" %}
{% block title %}
Your Portfolio
{% endblock %}
{% block main %}
<table class="table">
<thead>
<tr>
<th scope="col">Stock</th>
<th scope="col">Number of shares</th>
<th scope="col">Current price</th>
<th scope="col">Total value</th>
</tr>
</thead>
<tbody>
{% for stock in tableInfo %}
<tr>
<td>{{ stock.name }}</td>
<td>{{ stock.totalShares }}</td>
<td>{{ stock.price }}</td>
<td>{{ stock.value }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<table class="table">
<thead>
<tr>
<th scope ="col">Cash remaining</th>
<th scope ="col">Grand total</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ currentCash }}</td>
<td> {{ grandTotal }}</td>
</tr>
</tbody>
</table>
{% endblock %}
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,
I have my Django views.py function :
def dsctbl2(request):
dynamodb=boto3.client('dynamodb', region_name='us-west-2')
response = dynamodb.scan(
TableName='User-Account')
filtered = response['Items']
length = len(filtered)
a = []
for k in range(length):
accnum = filtered[k]['AccountNum']['S']
uid = filtered[k]['UserId']['S']
f = {}
f = dict(AccountNum=accnum,UserId=uid)
a.append(f)
return (a)
The above function filters the UserId and Accountnumber items from a dynamodb table. I need to display the "UserId" and "AccountNum" in my html template in a table's row.
Here's my html snippet :
<div class="mytable">
<table style="width:96%" class="table table-responsive">
<thead id="head" class="mdb-color lighten-4">
<tr>
<th></th>
<th class="th-lg">User ID</th>
<th class="th-lg">Account Number</th>
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
<th scope="row"></th>
<td>{{r.AccountNum}}</td>
<td>{{r.UserId}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
I've included block content and endblock tags in my html code . What am I doing wrong here ? I'm a beginner in Django. Thanks in advance
You need to render your output to your html file.
Ex:
from django.shortcuts import render_to_response
def dsctbl2(request):
dynamodb=boto3.client('dynamodb', region_name='us-west-2')
response = dynamodb.scan(
TableName='User-Account')
filtered = response['Items']
length = len(filtered)
a = []
for k in range(length):
accnum = filtered[k]['AccountNum']['S']
uid = filtered[k]['UserId']['S']
f = {}
f = dict(AccountNum=accnum,UserId=uid)
a.append(f)
return render_to_response('your.html', {"rows":a})
I am trying out this idea where there is a table of 'events' on a '/search' page and when a 'GO' button of an event is pressed, it will increment the 'RSVP' count of that event, and redirect back to '/search'. However, when I clicked on the 'GO' button in my application, it leads to a blank screen with url 'localhost:8080/rsvp'.
Finding it strange and wondering which part of my code is wrong. Here are some of the relevant parts of the code that I think is causing the error.
This is the code from the python file:
class RSVPItem(webapp2.RequestHandler):
# increment RSVP count when GO button is clicked
def post(self):
itemkey = ndb.Key('Items', self.request.get('itemid'))
item = itemkey.get()
item.rsvp = item.rsvp + 1
item.put()
self.redirect('/search')
# Handler for the Search page
class Search(webapp2.RequestHandler):
# Display search page
def get(self):
user = users.get_current_user()
if user: # signed in already
# Retrieve items
query = ndb.gql("SELECT * "
"FROM Items ")
template_values = {
'user_mail': users.get_current_user().email(),
'logout': users.create_logout_url(self.request.host_url),
'items': query,
}
template = jinja_environment.get_template('search.html')
self.response.out.write(template.render(template_values))
else:
self.redirect(self.request.host_url)
app = webapp2.WSGIApplication([('/', MainPage),
('/giftbook', MainPageUser),
('/wishlist', WishList),
('/deleteitem', DeleteItem),
('/search', Search),
('/rsvp', RSVPItem),
('/display', Display),
('/displaytag', Displaytag)],
debug=True)
This is from the html file for 'search.html'. Only showing the part I think is relevant.
<h4> Events List </h4>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th width="10%">Name</th>
<th>Description</th>
<th width = "10%">Link</th>
<th width = "10%">Date</th>
<th width = "10%">Type</th>
<th width = "10%">RSVP</th>
<th width = "10%">Rolling?</th>
</tr>
</thead>
<tbody>
{% for item in items %}
<tr>
<td>{{ item.event_name }} </td>
<td>{{ item.description }}</td>
<td>{{ item.event_link}}</td>
<td>{{ item.date.strftime('%Y-%m-%d') }}</td>
<td>{{ item.event_type}}</td>
<td>{{ item.rsvp }}
<td>
<form action="/rsvp" method="post">
<input type="hidden" name="itemid" value="{{ item.item_id }}">
<input type="submit" value="GO!">
</form></td>
</tr>
{% endfor %}
</tbody>
</table>
<form action="/rsvp" method="post"> sends them to /rsvp. Do you have a url handler for /rsvp?
Make sure you cast the Key to an int:
itemkey = ndb.Key('Items', int(self.request.get('itemid')))
Instead of setting your own id item_id, just use the built-in Key:
<input type="hidden" name="itemid" value="{{ item.key.id() }}">
Check the logs to see if there are any errors.
I'm having trouble with my project. I have 2 models
class UserPrefs(db.Model):
user = db.UserProperty()
name = db.StringProperty()
class Person(db.Model):
name = db.StringProperty()
phone = db.PhoneNumberProperty()
userPrefs = db.ReferenceProperty(UserPrefs)
class PersonHandler(webapp.RequestHandler):
def get(self):
users.get_current_user user = ()
if user:
greeting = ......
else:
greeting = ......
if self.request.GET.has_key ('id'):
id = int (self.request.get ['id'])
person = models.Person.get = (db.Key.from_path ('Person', id))
path = os.path.join (os.path.dirname (__file__), 'templates / doStuff.html')
self.response.out.write (template.render (path, locals (), debug = True))
def post (self):
if self.request.get ('Person'):
id = int (self.request.get ('Person'))
person = models.Person.get (db.Key.from_path ('Person', id))
else:
person= models.Person = ()
data = forms.PersonForm date = (data = self.request.POST)
if data.is_valid ():
if self.request.get ('photo'):
Person.foto db.Blob = (self.request.get ('photo'))
person.nome self.request.get = ('name')
person.apelido self.request.get = ('name')
person.unidade self.request.get = ('unit')
person.put ()
self.redirect ('/ doSomeStuff')
else:
self.redirect ('doOtherStuff')
To See the data in database i use this handler:
class SeePersonHandler (webapp.RequestHandler):
def get (self):
users.get_current_user user = ()
if user:
greeting = ......
else:
greeting = ......
person= db.Query(models.Pocente)
persons = person.fetch(limit = 1)
path = os.path.join(os.path.dirname(__file__), 'templates/SeeStuff.html')
self.response.out.write(template.render(path, locals(), debug = True))
Question:
I knows that the data is put corectly. I used the SDK Console with this url: http://localhost:8080/_ah/admin/datastore and the entity is created correctly. I donĀ“t know what i am missing to retrieve the dadta already put
My Template:
{% if user %}
{% if person%}
<table align="center">
<tbody>
<tr>
<td><input type="button" value="Criar Pessoa" onclick="redirect(3)" /></td>
</tr>
</tbody>
</table>
<table align="center">
<tbody>
<tr>
<td colspan="2"><center><strong><p>O meu Curriculum Vitae</p></strong></center></td>
</tr>
<tr>
<td>Nome: </td>
<td>{{ person.name}}</td>
</tr>
<tr>
<td>Apelido: </td>
<td>{{ person.phone}}</td>
</tr>
<tr>
<td></td>
<td>
<input type ="button" value="Editar" onclick="editarCv({{ person.key.id }})" />
</td>
</tr>
</tbody>
</table>
{% endif %}
{% endif %}
Your code is a bit disorganised.
Debugging is generally easier with better-organised code.
Anyway, enough of the trash-talking.
You're assigning the result of a datastore query to persons...
persons = person.fetch(limit = 1)
...but then in your template you use person:
<tr>
<td>Nome: </td>
<td>{{ person.name}}</td>
</tr>
<tr>
<td>Apelido: </td>
<td>{{ person.phone}}</td>
</tr>
It is difficult to tell if this is your only problem (I highly doubt it), but perhaps you can try fixing that and get back to us. Best of luck to you.
Aside: instead of .fetch(limit=1) you can simply use .get() as mentioned in the documentation:
get() implies a "limit" of 1. At most
1 result is fetched from the
datastore.