I created a django template with the following model
Models.py
class MaterialRequest(models.Model):
owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='allotment_sales')
product1 = models.CharField(max_length=500,default=0,blank=True,null=True)
product1_quantity = models.IntegerField(default=0,blank=True,null=True)
product2 = models.CharField(max_length=500,default=0, blank=True,null=True)
product2_quantity = models.IntegerField(default=0,blank=True,null=True)
product3 = models.CharField(max_length=500,default=0, blank=True,null=True)
product3_quantity = models.IntegerField(default=0,blank=True,null=True)
product4 = models.CharField(max_length=500,default=0, blank=True,null=True)
product4_quantity = models.IntegerField(default=0,blank=True,null=True)
product5 = models.CharField(max_length=500,default=0, blank=True,null=True)
product5_quantity = models.IntegerField(default=0,blank=True,null=True)
product6 = models.CharField(max_length=500,default=0, blank=True,null=True)
product6_quantity = models.IntegerField(default=0,blank=True,null=True)
product7 = models.CharField(max_length=500,default=0, blank=True,null=True)
product7_quantity = models.IntegerField(default=0,blank=True,null=True)
product8 = models.CharField(max_length=500,default=0, blank=True,null=True)
product8_quantity = models.IntegerField(default=0,blank=True,null=True)
and I tried displaying this data on the template using this view
def load_salesorder(request):
so_id = request.GET.get('sales_order')
s_o = MaterialRequest.objects.filter(pk=so_id)
print("kits=========",s_o)
return render(request, 'allotment_so.html', {'sales_order': s_o})
HTML
<table class="table table-bordered">
<thead>
<tr>
<th>Product Short Codes</th>
<th>Product Quantity</th>
</tr>
</thead>
<tbody>
<div class="table-container">
{% for i in sales_order %}
<tr>
<td class="align-middle">{{ i.product1 }}</td>
<td class="align-middle">{{ i.product1_quantity }}</td>
</tr>
<tr>
<td class="align-middle">{{ i.product2 }}</td>
<td class="align-middle">{{ i.product2_quantity }}</td>
</tr>
<tr>
<td class="align-middle">{{ i.product3 }}</td>
<td class="align-middle">{{ i.product3_quantity }}</td>
</tr>
<tr>
<td class="align-middle">{{ i.product4 }}</td>
<td class="align-middle">{{ i.product4_quantity }}</td>
</tr>
<tr>
<td class="align-middle">{{ i.product5 }}</td>
<td class="align-middle">{{ i.product5_quantity }}</td>
</tr>
<tr>
<td class="align-middle">{{ i.product6 }}</td>
<td class="align-middle">{{ i.product6_quantity }}</td>
</tr>
<tr>
<td class="align-middle">{{ i.product7 }}</td>
<td class="align-middle">{{ i.product7_quantity }}</td>
</tr>
<tr>
<td class="align-middle">{{ i.product8 }}</td>
<td class="align-middle">{{ i.product8_quantity }}</td>
</tr>
{% endfor %}
</tbody>
</table>
But the problem with is that it also shows the None values of ORM whereas I just want to show the fields that consists the data and leave out the blank values. How can I fix this and also is there a better way to do this ?
You can achieve that with some if statements in the template:
{% for i in sales_order %}
{% if i.product1 and i.product1_quantity %}
<tr>
<td class="align-middle">{{ i.product1 }}</td>
<td class="align-middle">{{ i.product1_quantity }}</td>
</tr>
{% endif %}
<!-- same for other fields -->
{% endfor %}
use can use if statement for each field:
<tr>
<td class="align-middle">{% if i.product1 %}{{ i.product1 }}{% endif %}</td>
<td class="align-middle">{% if i.product1_quantity %}{{ i.product1_quantity }}{% endif %}</td>
</tr>
Related
What I want to do is that for a particular Cylinder Id , if cylinder is issued then the user name and the issue date will be displayed in cylinder List , like this
cylinderId | date | type | status |availability| issuedate | userName | returndate |
1 | 11/11| co2 | fill | available| 12/11(if exists)| xyz | 13/11(if exists)
so for that i used prefetch_related but it is not displaying anything in cylinder List:-
here is model:-
class Cylinder(models.Model):
stachoice=[
('Fill','fill'),
('Empty','empty')
]
substachoice=[
('Available','available'),
('Unavailable','unavailable'),
('Issued','issued')
]
cylinderId=models.CharField(max_length=50,primary_key=True,null=False)
gasName=models.CharField(max_length=200)
cylinderSize=models.CharField(max_length=30)
Status=models.CharField(max_length=40,choices=stachoice,default='fill')
Availability=models.CharField(max_length=40,choices=substachoice,default="Available")
EntryDate=models.DateTimeField(default=timezone.now)
def get_absolute_url(self):
return reverse('cylinderDetail',args=[(self.cylinderId)])
def __str__(self):
return str(self.cylinderId)
class Issue(models.Model):
cylinder=models.ForeignKey('Cylinder',on_delete=models.CASCADE)
userName=models.CharField(max_length=60,null=False)
issueDate=models.DateTimeField(default=timezone.now)
def save(self,*args,**kwargs):
if not self.pk:
if self.cylinder.Availability=='Available':
Cylinder.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued'))
super().save(*args,**kwargs)
def __str__(self):
return str(self.userName)
here is cylinder list view:-
def cylinderListView(request):
cylinder=Cylinder.objects.all().prefetch_related('issue_set')
return render(request,'entry/cylinderList.html',locals())
here is cylinderList template:-
{% extends 'base.html'%}
{% block content %}
<div class="alldiv">
<h1 align="center">All Cylinder list</h1>
{% if cylinder %}
<div class='centerstage'>
<div class="post">
<table border="5" cellspacing="5" width="100%" >
<thead>
<tr bgcolor="#99c2ff"align="center">
<th height="50"
width="50">Cylinder Id</th>
<th height="50"
width="50">Date</th>
<th height="50"
width="50">Gas Name</th>
<th height="50"
width="50">Cylinder Size</th>
<th height="50"
width="50">Status</th>
<th height="50"
width="50">Availability</th>
<th height="50"
width="50">Issued Date</th>
<th height="50"
width="50">Customer</th>
<th height="50"
width="50">Return Date</th>
</thead>
<tbody>
{%for cy in cylinder%}
<tr bgcolor="#e6f0ff" align="center">
<td align="center" height="10"
width="50"><a href="{{cy.get_absolute_url}}">{{cy.cylinderId}}<a></td>
<td align="center" height="10"
width="50">{{cy.EntryDate}}</td>
<td align="center" height="10"
width="50">{{cy.gasName}}</td>
<td align="center" height="10"
width="50">
{{cy.cylinderSize}}</td>
<td align="center" height="10"
width="50">
{{cy.Status}}</td>
<td align="center" height="10"
width="50">{{cy.Availability}}</td>
<td align="center" height="10"
width="50">{{cy.issue.issueDate}}</td>
<td align="center" height="10"
width="50">{{cy.issue.userName}}</td>
</tr>
{% endfor %}
</tbody>
{% else %}
<div>
<h2>No record</h2>
</div>
</table>
</div>
</div>
</div>
{% endif %}
{% endblock %
}
I m unable to figure out that what i m missing , Is I m using prefetch_related?
You need to cycle through the issue_set like so:
{% for issue in cy.issue_set.all() %}
<td align="center" height="10" width="50">{{ issue.issueDate }}</td>
<td align="center" height="10" width="50">{{ issue.userName }}</td>
{% endfor %}
i want to display my query from SQLite3 into Bootstrap Table. but it seems doesnt work and wont display the table.
herewith my code
views.py
#main.route('/currentlist', methods=["GET"])
def current():
if request.method == 'GET':
Connection = sqlite3.connect('C:\\Backup_old\\Task\\e_ticket\\my_app\\db\\customer.db')
cursor = Connection.cursor()
query2 = "SELECT * from customer"
cursor.execute(query2)
test = cursor.fetchall()
return render_template('overview.html', testform = test)
HTML
<div class= "content">
<table id="dtBasicExample" class="table" width="100%">
<thead>
<tr>
<th class="th-sm">Date
</th>
<th class="th-sm">time
<th class="th-sm">customer
</th>
<th class="th-sm">pic
</th>
<th class="th-sm">category
</th>
<th class="th-sm">description
</th>
</tr>
</thead>
<tbody>
<tr>
<td>9 December 2021</td>
<td>15:30:00</td>
<td>AB Corp.</td>
<td>Bob</td>
<td>network</td>
<td>network is down</td>
</tr>
<tr>
<td>9 December 2021</td>
<td>17:30:00</td>
<td>AB Corp.</td>
<td>Alex</td>
<td>computer</td>
<td>computer is broken</td>
</tr>
<tr>
<td>10 December 2021</td>
<td>05:32:00</td>
<td>CD Corp.</td>
<td>Bob</td>
<td>Server</td>
<td>server is down</td>
</tr>
<tr>
<td>12 December 2021</td>
<td>10:30:00</td>
<td>AB Corp.</td>
<td>Bob</td>
<td>printer</td>
<td>printer is down</td>
</tr>
</tbody>
</table>
</div>
it should be like this but with the data from DB
enter image description here
i've read many similiar question like this, but most of them use SQLAlchemy.
Any help greatly appreciated!
You need to use a loop and template variables with the data.
<tbody>
{% for row in testform %}
<tr>
<td>{{ row[0] }}</td>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
<td>{{ row[3] }}</td>
<td>{{ row[4] }}</td>
<td>{{ row[5] }}</td>
</tr>
{% endfor %}
</tbody>
How do I parse through this json data in a more efficient way. I'd like to do it with a for loop so the code doesn't repeat itself.
Here's the data endpoint: https://api.coingecko.com/api/v3/exchange_rates
and the json response sample:
{
"rates": {
"btc": {
"name": "Bitcoin",
"unit": "BTC",
"value": 1,
"type": "crypto"
},
"eth": {
"name": "Ether",
"unit": "ETH",
"value": 48.316,
"type": "crypto"
},
"ltc": {
"name": "Litecoin",
"unit": "LTC",
"value": 169.967,
"type": "crypto"
}
my view.py code:
def btc_to_currency(request):
exchange_endpoint = "https://api.coingecko.com/api/v3/exchange_rates"
request_exchange_data = requests.get(exchange_endpoint)
results_exchange_data = request_exchange_data.json()
data_exchange = results_exchange_data["rates"]
#print(data_exchange)
btc = (data_exchange['btc'])
xrp = (data_exchange['xrp'])
xau = (data_exchange['xau'])
xag = (data_exchange['xag'])
return render(request, 'crypto/btc_to_currency.html', {'btc' : btc, 'xrp': xrp, 'xau': xau, 'xag': xag})
and my template html code:
<table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
<thead>
<tr>
<th rowspan="2" class="is-size-7 has-text-centered">Name</th>
<th rowspan="2" class="is-size-7 has-text-centered">Unit</th>
<th rowspan="2" class="is-size-7 has-text-centered">Value</th>
<th rowspan="2" class="is-size-7 has-text-centered">Type</th>
</tr>
</thead>
{% load humanize %}
<tbody>
<tr>
<th class="is-size-7 has-text-centered"><strong>{{ btc.name }}</strong></th>
<td class="has-text-centered">{{ btc.unit }}</td>
<td class="has-text-centered">{{ btc.value }}</td>
<td class="has-text-centered">{{ btc.type }}</td>
</tr>
<tr>
<th class="is-size-7 has-text-centered"><strong>{{ xrp.name }}</strong></th>
<td class="has-text-centered">{{ xrp.unit }}</td>
<td class="has-text-centered">{{ xrp.value|intcomma }}</td>
<td class="has-text-centered">{{ xrp.type }}</td>
</tr>
<tr>
<th class="is-size-7 has-text-centered"><strong>{{ xau.name }}</strong></th>
<td class="has-text-centered">{{ xau.unit }}</td>
<td class="has-text-centered">{{ xau.value }}</td>
<td class="has-text-centered">{{ xau.type }}</td>
</tr>
<tr>
<th class="is-size-7 has-text-centered"><strong>{{ xag.name }}</strong></th>
<td class="has-text-centered">{{ xag.unit }}</td>
<td class="has-text-centered">{{ xag.value }}</td>
<td class="has-text-centered">{{ xag.type }}</td>
</tr>
</tbody>
</table>
I've been able to parse other json data using a forloop, but the structure was different. it was a list of dictionaries like this below:
[
{
"id": "bitcoin",
"symbol": "btc",
"name": "Bitcoin",
"image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
"current_price": 6915.62
}
]
for that I used:
def latest(request):
per_page_limit = int(request.GET.get('limit', 10))
coin_list_url = f"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page={per_page_limit}&page=1&sparkline=false"
request_coin_list = requests.get(coin_list_url)
results_coin_list = request_coin_list.json()
crypto_data_geckco = []
for currency_gecko in results_coin_list:
crypto_data_geckco.append(currency_gecko)
return render(request, 'crypto/latest.html', { 'crypto_data_geckco': crypto_data_geckco} )
and then in the template:
{% for currency in crypto_data_geckco %}
<div class="box">
<article class="media">
<div class="media-left is-size-4">
<figure class="image is-96x96">
<img src="{{ currency.image }}" alt="Crypto Image Logo">
</figure>
<br>
<br>
<small><strong>{{ currency.name }} ({{ currency.symbol|upper }})</strong></small>
<br>
<span class="tag is-dark is-medium"><small><strong>Rank: #{{ currency.market_cap_rank }}</strong></small></span>
</div>
{% load humanize %}
{% load mathfilters %}
<div class="media-content">
<div class="content media-right is-size-6">
<br>
<strong>{{ currency.name }} ${{ currency.current_price }}</strong>
<br>
<strong>Market Cap:</strong> {{ currency.market_cap|intword }}
<br>
<hr>
<strong>24h Low / 24h High:</strong> ${{ currency.low_24h }} / ${{ currency.high_24h }}
<br>
<strong>24h Price Change:</strong> ${{ currency.price_change_24h }}
<br>
<strong>24h Price Change (%):</strong> {{ currency.price_change_percentage_24h|floatformat:2|intcomma }}%
<br>
<hr>
<strong>Trading Volume (24hr):</strong> ${{ currency.total_volume|intword }}
<br>
<strong>Volume / Market Cap:</strong> {{ currency.total_volume|div:currency.market_cap|floatformat:3|intcomma }}
<br>
That worked fine.
thanks
#ThierryLathuille comment was correct and solved the issue.
Then in the html template I was able to access the data with a for loop:
<table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth">
<thead>
<tr>
<th rowspan="2" class="is-size-7 has-text-centered">Name</th>
<th rowspan="2" class="is-size-7 has-text-centered">Unit</th>
<th rowspan="2" class="is-size-7 has-text-centered">Value in BTC</th>
<th rowspan="2" class="is-size-7 has-text-centered">Type</th>
</tr>
</thead>
{% for exchange in data_exchange.values %}
{% load humanize %}
<tbody>
<tr>
<th class="is-size-7 has-text-centered"><strong>{{ exchange.name }}</strong></th>
<td class="has-text-centered">{{ exchange.unit }}</td>
<td class="has-text-centered">{{ exchange.value|intword|intcomma }}</td>
<td class="has-text-centered">{{ exchange.type }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I am trying to display data on my web app from a CSV file using Flask. The below code reads my CSV file and assigns stocklist as the variable for my data. In the HTML code below it, using jinga logic, I iterate through stocklist however my CSV columns are returned as rows (see sample output and pic). How do I display the rows correctly?
My python function:
#app.route('/stocks')
def Stocks():
filename = 'stock_scraper - dev.csv'
data = pandas.read_csv(filename, header=0)
stocklist = list(data.values.flatten())
return render_template('stocks.html', stocklist=stocklist)
My web app for iterating through stocklist:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Ticker</th>
<th>Closing Price</th>
<th>Closing Date</th>
</tr>
</thead>
<tbody>
{% for eachstocks in stocklist%}
<tr>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
<td>{{ eachstocks }}</td>
</tr>
{% endfor %}
</tbody>
</table>
Output:
Haks, i removed the nested loop and added the list position in each value to fix it. Works now.
<tbody>
{% for value in stocklist %}
<tr>
<td>{{ value[0] }}</td>
<td>{{ value[1] }}</td>
<td>{{ value[2] }}</td>
<td>{{ value[3] }}</td>
</tr>
{% endfor %}
</tbody>
output
enter image description here
You shouldn't flatten the list.
Try this:
#app.route('/stocks')
def Stocks():
filename = 'stock_scraper - dev.csv'
data = pandas.read_csv(filename, header=0)
stocklist = list(data.values)
return render_template('stocks.html', stocklist=stocklist)
Then for the Jinja template:
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Ticker</th>
<th>Closing Price</th>
<th>Closing Date</th>
</tr>
</thead>
<tbody>
{% for value in stocklist%}
<tr>
<td>{{ value[0] }}</td>
<td>{{ value[1] }}</td>
<td>{{ value[2] }}</td>
<td>{{ value[3] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
I have this problem where I can't display the contents of a dictionary into a webpage.
web_indiv[url_sequence] = {'url' : converted_url , 'name' : x.name, 'count' : web_count_current }
return render_template('video.html', web_data = web_indiv)
The web_indiv is populated using a loop, and then passed to video.html as web_data.
Sample dictionary
{1: {'url': 'http://www.drpeppersnapplegroup.com/', 'name': 'Dr. Pepper-Snapple Group', 'count': 57}, 2: {'url': 'http://www.rccolainternational.com/', 'name': 'Royal Crown Cola', 'count': 41}}
Note: It is a dictionary that contains another dictionary inside it.
This is what I already have on my html file.
{% for key1,line in web_data.items() %}
{% for key2,line_item in line.items() %}
<tr>
<td class="col-md-2">{{ line_item['url'] }}</td>
<td class="col-md-2">{{ line_item['name'] }}</td>
<td class="col-md-2">{{ line_item['count'] }}</td>
</tr>
{% endfor %}
{% endfor %}
Data won't display on the webpage.
Thank you for taking time to read my query.
If it is just a dict, you could try this:
<html>
{{web_data[url_sequence]}}
<table>
<tr>
{%for value in web_data[url_sequence].values()%}
<td class="col-md-2">{{ value }}</td>
{% endfor %}
</tr>
</table>
</html>
Note that the web_data[url_sequence] is a dictionary.
This one will have the orders (url, name and then count):
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
Real example:
Suppose you have the dictionary web_indiv, then you want to render it to template video.html
#app.route('/', methods=['GET'])
def root():
web_indiv = {}
url_sequence = 'test'
web_indiv[url_sequence] = {'url':'testabc','name':'hello','count': 4}
return render_template('video.html', web_data = web_indiv, url_sequence = url_sequence)
Then you can use the dict in template like this:
<tr>
<td class="col-md-2">{{ web_data[url_sequence].url }}</td>
<td class="col-md-2">{{ web_data[url_sequence].name }}</td>
<td class="col-md-2">{{ web_data[url_sequence].count }}</td>
</tr>
The html will show you:
testabc hello 4
{% for key2,line_item in web_data[url_sequence].items %}
<tr>
<td class="col-md-2">{{ line_item }}</td>
</tr>
{% endfor %}