uniqe and repeated values in HTML table using Python/Django - python

I need to build two 3x3 tables with numbers from 1 to 9. One table should have unique values.
I'm only able to get first table workin with {{ random_number }} and can't figure out what's wrong with the other one {{unique_random_number}}. I'm getting THIS.
Here's my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'devtask1.views.index'),
url(r'^$', 'devtask1.views.index2'),
)
views.py
from django.shortcuts import render_to_response
from random import randint
def n():
return randint(1,9)
def index(request):
return render_to_response('index.html', {'random_number': n})
def un():
for i in range(1,10):
return i
def index2(request):
return render_to_response('index.html', {'unique_random_number': un})
index.html
<table>
<tr>
<td>{{ random_number }}</td>
<td>{{ random_number }}</td>
<td>{{ random_number }}</td>
</tr>
<tr>
<td>{{ random_number }}</td>
<td>{{ random_number }}</td>
<td>{{ random_number }}</td>
</tr>
<tr>
<td>{{ random_number }}</td>
<td>{{ random_number }}</td>
<td>{{ random_number }}</td>
</tr>
</table>
<table>
<tr>
<td>{{ unique_random_number }}</td>
<td>{{ unique_random_number }}</td>
<td>{{ unique_random_number }}</td>
</tr>
<tr>
<td>{{ unique_random_number }}</td>
<td>{{ unique_random_number }}</td>
<td>{{ unique_random_number }}</td>
</tr>
<tr>
<td>{{ unique_random_number }}</td>
<td>{{ unique_random_number }}</td>
<td>{{ unique_random_number }}</td>
</tr>
</table>

Why not pass unique random number by building an array shuffling it and passing it through the context.
import random
def un():
unums = []
for i in range(1,10):
unums.append(i)
random.shuffle(unums)
return unums
then in your html call the index, unique_random_number[0] through unique_random_number[9] they'll always be different because of the shuffle but you'll avoid the repeats.
Also, using django that table can be accomplished with a for loop much cleaner.

Related

How to delete table content from sqlite Django

I want to delete the data when pressing the trash bin button. I am able to submit, edit petty cash into the database. I am only left with deleting the data.
This is my views.py
def deleteclaims(request, id):
context = initialize_context(request)
user = context['user']
#get id of particular form.
claims = SaveClaimForm.objects.get(id=id)
if request.method == 'POST':
claims.name = request.POST['name']
claims.email = request.POST['email']
claims.claim = request.POST['claim']
claims.claimtype = request.POST.get('claimtype')
claims.description = request.POST['description']
claims.receipt = request.FILES['receipt']
claims.cheque = request.POST.get('Cheque')
claims.status = request.POST['status']
claims.delete()
claims.save()
return render(request, 'Login/existingclaims.html', {'claims':claims, 'user':user}, {'action' : 'Delete claims'})
In my html
<tr align="center">
<td>{{ claims.id }}</td>
<td>{{ claims.name }}</td>
<td>{{ claims.email }}</td>
<td>{{ claims.claim }}</td>
<td>{{ claims.claimtype }}</td>
<td>{{ claims.description }}</td>
<td> Click to View </td>
<td>{{ claims.cheque }}</td>
<td>{{ claims.status }}</td>
<td><i class="fas fa-pencil-alt"></i></td>
<td><i class="fas fa-trash"></i></td>
</tr>

Fetching and display the data in a Django Template Using MYSQL RAW SQL QUERY

Here is my Django Template Used to Display The data in table Format...
enter code here
<table class="content" border="2px">
<thead>
<tr>
<th>S-No</th>
<th>Name</th>
<th>Email</th>
<th>Productname</th>
<th>Quantity</th>
<th>Price</th>
<th>Ordertime</th>
<th>Orderstatus</th>
<th>Actions</th>
</tr></thead>
<tbody>
{% for row in records %}
<tr align="center">
<td>{{row.pid}}</td>
<td>{{ row.username }}</td>
<td>{{ row.email }}</td>
<td>{{ row.productname }}</td>
<td>{{ row.quantity }}</td>
<td>{{ row.price }}</td>
<td>{{ row.ordertime }}</td>
<td>{{ row.orderstatus }}</td>
<td><input type="submit" value="Accept"> <input type="button" value="Reject"></td>
</tr>
{% endfor %}
</tbody>
</table>
And This is my Views.py Page for the fetching up of the data
def viewpro(request):
con = mysql.connector.connect(user='root', password='', host='localhost', database='company1')
cur = con.cursor()
cur.execute("SELECT * FROM user_order")
records=cur.fetchall()
print(records)
con.commit()
cur.close()
con.close()
#context = {'viewpro' : user_order.objects.all()}
return render(request, "viewpro.html", {'records':records})
But Here The problem is it display the no.of table rows same like DB(It have 4 records and table shows 4 rows But no data in the fields).....Pls Help me to get rid of that....Only using raw queries....

How to pass certain key and value of a python dictionary to HTML script

I am using flask and in one endpoint I just pass the following dictionary to html file:
app = Flask(__name__)
#app.route("/home")
def home():
q = {"id":23,
"path": '/usr/test.py',
"mynum": 22}
return render_template("home.html", query=q)
in HTML file:
{% for value in query.values() %}
<td>{{ value }}</td>
{% endfor %}
But in this way I am passing all the key-value's but I need to pass certain key-values. More clear, I expect such a solution in HTML if exist:
<td>{{ query["path"] }}</td>
<td>{{ query["id"] }}</td>
<td>{{ query["mynum"] }}</td>
I also tried this:
<td>{{ query.path }}</td>
<td>{{ query.id }}</td>
<td>{{ query.mynum }}</td>
but prints query.path, query.id , query.mynum rather than values
Printing dictionary specific key's value in Jinja2 template without loop
If you want to print specific key of a dictionary, you may use .get() method.
app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route("/home")
def home():
q = {"id":23,"path": '/usr/test.py',"mynum": 22}
return render_template("home.html", query=q)
home.html:
<table>
<tr>
<th>ID</th>
<th>Path</th>
<th>Number</th>
</tr>
<tr>
<td>{{ query.get("id") }}</td>
<td>{{ query.get("path") }}</td>
<td>{{ query.get("mynum") }}</td>
</tr>
</table>
Output:
If the key is not found in the dictionary it will print None as value. You may also pass default value as second parameter of the get method.
E.g.:
{{ query.get("arsho", "Value not found") }}
It looks like the issue you are dealing with is that the order of the key/values in the dictionary is not the same order that you would like to display. Instead of hard-coding the <td> elements, you can create a list of the keys in the order you want them to appear and pass that to the template.
import jinja2
query = {"id":23,
"path": '/usr/test.py',
"mynum": 22}
ordered_keys = ('path', 'id', 'mynum')
h = '''<table><tr>
{% for k in ordered_keys -%}
<td>{{ query.get(k, '') }}</td>
{% endfor -%}
</tr></table>
'''
t = jinja2.Template(h)
print(
t.render(query=query, ordered_keys=ordered_keys)
)
# prints:
<table><tr>
<td>/usr/test.py</td>
<td>23</td>
<td>22</td>
</tr></table>

Reading a CSV file in Flask and iterating through Jinga2

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>

How can I iterate multiple key from a dictionary in Django template

I have given data from views to template in django. I want to iterate these multiple keys to build a html table.
views.py
data={'pacientes':p,'inicios':i,'finales':f,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)
I want to do something like
index.html
<table>
{% for p, i, f in pacientes, inicios, finales %} # I know that this code is not work
<tr>
<td>{{ p.nombre }}</td>
<td>{{ i }}</td>
<td>{{ f }}</td>
<tr>
{% endfor %}
</table>
p is an object from Pacientes
class Usuario(models.Model):
dni=models.CharField(max_length=9,primary_key=True)
clave=models.CharField(max_length=16)
nombre=models.CharField(max_length=30)
...
and i is a string's list as
('20-2-2014', '12-2-2014', ..., '11-5-2014')
I suppose that each index of paciente, inicio and finales are related between them.
Just as Ignacio says, you can write some code in the view, before passing it to the template in order to solve your problem.
A possible solution could be packing the values in a list of tuples like this:
[
(pacientes[0], inicios[0], finales[0]),
(pacientes[1], inicios[1], finales[1]),
...
]
You can achieve this easily by using the zip function in your view:
pacientes_data = zip(p, i, f)
data={'pacientes_data':pacientes_data,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)
And in your template:
<table>
{% for p,i,f in pacientes_data %}
<tr>
<td>{{ p.nombre }}</td>
<td>{{ i }}</td>
<td>{{ f }}</td>
</tr>
{% endfor %}
</table>
Here is a working solution for similar task:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Model Name</th>
<th scope="col">Device Count</th>
</tr>
</thead>
<tbody>
{% for all_model in all_models %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td>{{ all_model.0 }}</td>
<td>{{ all_model.1 }}</td>
</tr>
{% endfor %}
</tbody>
</table>
In view.py
all_models = []
all_models_names = [1,2,3,4]
all_models_names_values = [1,2,3,4]
all_models = zip(all_models_names,all_models_names_values)
return render(request, "sample.html",{'all_models':all_models})

Categories