How to delete table content from sqlite Django - python

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>

Related

flask, page doesn't exist

I have deployed my model. But when i click the submit button I’m not shown the predictions but rather an error that the page doesn’t exist. Please help me. `
This is the app.py code
movies = pd.read_csv('movies.csv')
app = flask.Flask(__name__, template_folder='templates')
count = CountVectorizer()
count_matrix = count.fit_transform(movies['All_Words'])
cosine_sim = cosine_similarity(count_matrix, count_matrix)
indices = pd.Series(movies.index)
all_titles = [movies['Title'][i] for i in range(len(movies['Title']))]
def recommendations(Title, cosine_sim = cosine_sim):
recommended_movies = []
idx = indices[indices == Title].index[0]
score_series = pd.Series(cosine_sim[idx]).sort_values(ascending = False)
top_10_indexes = list(score_series.iloc[1:11].index)
# populating the list with the titles of the best 10 matching movies
for i in top_10_indexes:
recommended_movies.append(list(movies.index)[i])
return recommended_movies
def get_recommendations(Title):
cosine_sim = cosine_similarity(count_matrix, count_matrix)
idx = indices[Title]
sim_scores = list(enumerate(cosine_sim[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
sim_scores = sim_scores[1:11]
movie_indices = [i[0] for i in sim_scores]
tit = movies['Title'].iloc[movie_indices]
dat = movies['All_Words'].iloc[movie_indices]
return_df = pd.DataFrame(columns=['Title','All_Words'])
return_df['Title'] = tit
return_df['All_Words'] = dat
return return_df
#app.route('/', methods=['GET', 'POST'])
def main():
if flask.request.method == 'GET':
return(flask.render_template('mainpage.html'))
if flask.request.method == 'POST':
m_name = flask.request.form['movie_name']
m_name = m_name.title()
#if m_name in all_titles:
#return(flask.render_template('negative.html',name=m_name))
result_final = recommendations(m_name)
names = []
names.append(result_final)
return flask.render_template('positive.html',movie_names=names,search_name=m_name)
if __name__ == '__main__':
app.run()
This is the mainpage.html
!-- Demo -->
<div class="movie">
<h2 style="color:black;">Movie Recommendation System</h2>
<form action="{{ url_for('main') }}" method="POST">
<input type="text" id="movie_name" name="movie_name" placeholder="Enter movie name" required />
<input type="submit" id="submission_button" value="Submit"/>
</form>
This is the positive.html
<div class="movie">
<h2><b>RECOMMENDATIONS</b></h2>
<p>Showing results for: {{ search_name }}</p>
<table class="movie_table" align="center">
<tr>
<th>Movie Title</th>
</tr>
<tbody class="table_body">
<tr>
<td>{{ movie_names[0] }}</td>
</tr>
<tr>
<td>{{ movie_names[1] }}</td>
</tr>
<tr>
<td>{{ movie_names[2] }}</td>
</tr>
<tr>
<td>{{ movie_names[3] }}</td>
</tr>
<tr>
<td>{{ movie_names[4] }}</td>
</tr>
<tr>
<td>{{ movie_names[5] }}</td>
</tr>
<tr>
<td>{{ movie_names[6] }}</td>
</tr>
<tr>
<td>{{ movie_names[7] }}</td>
</tr>
<tr>
<td>{{ movie_names[8] }}</td>
</tr>
<tr>
<td>{{ movie_names[9] }}</td>
</tr>
</tbody>
</table>
Please help me. When i click submit i want my suggestions to be displayed in a tabular form.

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....

Django : cannot retrieve numbers of objects

I am working on a Django (v1.11.0) project and I have this model called Album which allows every user to add albums.
I wrote the following to display the number of authenticated user, however nothing showed
#login_required()
def user_account(request):
user = request.user
user_albums = Album.objects.filter(user=request.user)
nb_albums = 0
for i in user_albums:
nb_albums = nb_albums + 1
context = {
'nb_albums': nb_albums
}
return render(request, 'music/user_account.html', {'user': user}, context)
Here is the code in the HTML page:
<td>{{ request.user }}</td>
<td>{{ request.user.first_name }}</td>
<td>{{ request.user.last_name }}</td>
<td>{{ request.user.email }}</td>
<td>{{ nb_albums }}</td>
Change your code:
#login_required()
def user_account(request):
user_albums = Album.objects.filter(user=request.user)
nb_albums = user_albums.count()
return render(request, 'music/user_account.html', {'nb_albums': nb_albums})
and for your template:
<td>{{ user }}</td>
<td>{{ user.first_name }}</td>
<td>{{ user.last_name }}</td>
<td>{{ user.email }}</td>
<td>{{ nb_albums }}</td>

Cannot get HTML to display SQLite3 data with python & flask

I'm having an issue getting an HTML page to display my SQLite3 data using Python & Flask. I found a question on here and used the same code, plus different variations to no success. There are no error messages and the HTML page loads, however there is no data present. This is the code I am using to get the data;
#app.route("/viewpackages", methods=['GET'])
def viewpackages():
con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson,"
"shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
return render_template("view_packages.html", items=getpackages.fetchall())
this is the code I attempting to use to display the data;
<table>
{% for item in items %}
<tr>
<td>{{column1}}</td>
<td>{{column2}}</td>
<td>{{column3}}</td>
<td>{{column4}}</td>
<td>{{column5}}</td>
<td>{{column6}}</td>
<td>{{column7}}</td>
<td>{{column8}}</td>
</tr>
{% endfor %}
</table>
I tried changing 'column' to the actual db column name, with the same issue. I tried calling SELECT * instead of each individual column, same issue. If I run this code in python;
con = sqlite3.connect('utpg.db')
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson, shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
packages = getpackages.fetchall()
for row in packages:
print(row)
It returns the desired results. So I am thinking there is an issue with the HTML somewhere but I cannot figure it out.
Please try the following code and let me know if it works for you:
<table>
{% for item in items %}
<tr>
<td>{{ item[0] }}</td>
<td>{{ item[1] }}</td>
<td>{{ item[2] }}</td>
<td>{{ item[3] }}</td>
<td>{{ item[4] }}</td>
<td>{{ item[5] }}</td>
<td>{{ item[6] }}</td>
<td>{{ item[7] }}</td>
</tr>
{% endfor %}
</table>
Test with the following code:
app.py
from flask import Flask, render_template
import sqlite3
app = Flask(__name__)
app.secret_key = 'development key'
#app.route('/users')
def get_users():
con = sqlite3.connect('mydb.db')
db = con.cursor()
db.execute('insert into user values ("Aaa", "AAA")')
db.execute('insert into user values ("Bbb", "BBB")')
res = db.execute('select * from user')
return render_template('users.html', users=res.fetchall())
if __name__ == "__main__":
app.run(host="0.0.0.0", debug=True)
templates/users.html
<html !DOCTYPE>
<head>
<title>SQLite</title>
</head>
<body>
<table>
{% for user in users %}
<tr>
<td>{{ user[0] }}</td>
<td>{{ user[1] }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
Here is what I had to do.. For anyone else having this issue, I'm not sure why but Jinja did not want to let me access by index so I did..
#app.route("/viewpackages", methods=['GET'])
def viewpackages():
con = sqlite3.connect('utpg.db')
con.row_factory = sqlite3.Row
db = con.cursor()
user_id = session.get('id')
getpackages = db.execute("SELECT pck_id, client_id, date, price, privatelesson,"
"shortgamelesson, playinglesson, notes FROM packages WHERE client_id = ?;", (user_id, ))
return render_template("view_packages.html", items=getpackages.fetchall())
and change the HTML to..
<table>
{% for col in items %}
<tr>
<td>{{ col['pck_id'] }}</td>
<td>{{ col['client_id'] }}</td>
<td>{{ col['date'] }}</td>
<td>{{ col['price'] }}</td>
<td>{{ col['privatelesson'] }}</td>
<td>{{ col['shortgamelesson'] }}</td>
<td>{{ col['playinglesson'] }}</td>
<td>{{ col['notes'] }}</td>
</tr>
{% endfor %}
</table>
All working now, thank for pointing me in the right direction!

uniqe and repeated values in HTML table using Python/Django

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.

Categories