flask, page doesn't exist - python

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.

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>

Flask Jinja notation to return html content not html tags

The jinja notation in my html template:
<table border="1" class="dataframe table table-sm table-hover">
...
{% for a in REC %}
<tr>
<td>{{ a[0] }}</td>
<td>{{ a[1] }}</td>
<td><input type="password" value="{{ a[2] }}" id="myInput" class="receipts"></td>
<td>{{ a[3] }}</td>
<td>{{ a[4] }}</td>
...
...
</table>
The Visit W3Schools.com! is what has been entered into the database. Instead, of the tags being shown, I actually just want the html output to be shown i.e. Visit W3Schools.com!
How do I change the jinja {{ a[4] }} to do this?
The app route serving the template:
#app.route('/<string:_id>/rec')
def rec(_id):
mydb = mysql.connector.connect(host="...",user="...",passwd="...")
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM Receipts ORDER BY Date;")
REC = mycursor.fetchall()
mydb.close()
return render_template('two.html',REC=REC,_id=_id)
Many thanks
Use safe
Ex:
<table border="1" class="dataframe table table-sm table-hover">
...
{% for a in REC %}
<tr>
<td>{{ a[0] }}</td>
<td>{{ a[1] }}</td>
<td><input type="password" value="{{ a[2] }}" id="myInput" class="receipts"></td>
<td>{{ a[3] }}</td>
<td>{{ a[4]|safe }}</td>
...
...
</table>

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

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