I am trying to delete a record in a database when a yes button is clicked using django.
views.py
def deleteServer(request, server_id):
server = Server.objects.get(pk=server_id)
print(request.POST)
if request.POST.get('yesBtn'):
server.delete()
return HttpResponseRedirect('homepage')
elif request.POST.get('noBtn'):
return HttpResponseRedirect('homepage')
return render(request, 'deleteServer.html', {'value': request.POST})
deleteServer.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Cancella server</title>
</head>
<body>
<button onclick="document.getElementById('id01').style.display='block'"
class="w3-button">Cancella server</button>
<!-- The Modal -->
<div id="id01" class="w3-modal">
<div class="w3-modal-content">
<div class="w3-container">
<span onclick="document.getElementById('id01').style.display='none'"
class="w3-button w3-display-topright">×</span>
<p>Vuoi davvero cancellare il server selezionato?</p>
SI
NO
</div>
</div>
</div>
</body>
</html>
When I click on the yes button the record is not deleted. I thought the problem is in the deleteServer function in the file views.py.
EDIT
I printed the results of request.GET and the output is QueryDict = {}
You just have to pass the values in the GET.. Normally it's like ?key=value and if you have multiple its ?key0=value0&key1=value1
SI
NO
Note: the =True doesn't matter, It could be literally anything because in the view it just looks ~"Is key in GET" and doesn't actually look at the value itself
Edit
I completely missed that your view used request.POST.get(x)
It should use request.GET.get(x)
def deleteServer(request, server_id):
server = Server.objects.get(pk=server_id)
print('POST:', request.POST)
print('GET:', request.GET)
if request.GET.get('yesBtn'):
server.delete()
return HttpResponseRedirect('homepage')
elif request.GET.get('noBtn'):
return HttpResponseRedirect('homepage')
return render(request, 'deleteServer.html', {'value': request.POST})
Related
I used python to render a very simple html page. In the html page, I made a link that is supposed to send you to another page. The first html page works, however, when I click on the link it sends me to a 404 page not found error. My index.html and about.html are in a folder called templates. Here is how it looks: enter image description here
Here is my code:
app.py:
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Don's first website :D">
<title>Don's website</title>
<style>
</style>
</head>
<body>
other website
</body>
</html>
contact.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>hello</title>
</head>
<body>
<h1>please work!</h1>
</body>
</html>
You need to create a route for each template.
app = Flask(__name__)
#app.route('/')
def home():
return render_template('index.html')
#app.route('/contact')
def contact():
return render_template('contact.html')
if __name__ == "__main__":
app.run(debug=True)
replace your href in your contact template to the following
<a href="{{ url_for('contact') }}">
I am learning flask & have created a very basic page which renders Jokes from the pyjokes library
Here my doubt is though the jokes are populating in the list but all the items are having 1. in front of them how can I increase these number
Python code
from flask import Flask, redirect, url_for, render_template
import pyjokes
import sys
app = Flask(__name__)
jokes = pyjokes.get_jokes()
# Defining the home page of our site
#app.route("/") # this sets the route to this page
def home():
# print(jokes)
return render_template("1.html" , jokes = jokes) # some basic inline html
#app.route("/<anything>")
def user(anything):
return f"Hello {anything}! plz go back nothing here "
if __name__ == "__main__":
app.run(use_reloader=True,debug=True)
HTML Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Welcome to home page</h1>
<h3>Below are jokes frok python modules jokes</h3>
{% for x in jokes %}
<ol><li>{{x}}</li></ol>
{% endfor %}
</body>
</html>
Sample Current Output
Welcome to home page
Below are jokes frok python modules jokes
1.Complaining about the lack of smoking shelters, the nicotine addicted Python programmers said 1.there ought to be 'spaces for tabs'.
1.Ubuntu users are apt to get this joke.
1.Obfuscated Reality Mappers (ORMs) can be useful database tools.
& so on ...
Expected Output
Welcome to home page
Below are jokes frok python modules jokes
1.Complaining about the lack of smoking shelters, the nicotine addicted Python programmers said 1.there ought to be 'spaces for tabs'.
2.Ubuntu users are apt to get this joke.
3.Obfuscated Reality Mappers (ORMs) can be useful database tools.
& so on ...
Try this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Welcome to home page</h1>
<h3>Below are jokes frok python modules jokes</h3>
<ol>
{% for x in jokes %}
<li>{{x}}</li>
{% endfor %}
</ol>
</body>
</html>
Looks like you're creating a new ordered list for each element, instead of one ordered list with all the elements contained in it.
from flask import Flask, render_template, url_for, jsonify, request
from translate import Translator
en_ge = Translator("geo")
ge_en = Translator("en","geo")
app = Flask("Translator")
#app.route("/send",methods=["GET","POST"])
def send():
if request.method == "POST":
word = request.form["word"]
return render_template("translator.html",word=en_ge.translate(f"{word}"))
return render_template("index.html")
app.run()
I am trying to make translator with flask, but unfortunately I start learning it 10 minutes ago :). I am just trying to win a bet and make it as fast as I can. Googled but I keep receiving server internal error. How to fix it, please help
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Translator</title>
</head>
<body>
<h1>შეიყვანე სიტყვა</h1>
<form method="POST" action="/send">
<div class="form-group">
<input type="text" name="word">
</div>
<input class="btn btn-primary" type="submit" value="Translate">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>{{word}}</h1>
</body>
</html>
I think u miss template_folder param in Flask object creation, something like
app = Flask("Translator", template_folder="full_path_fo_a_folder_where_your_html_is_stored")
I have a Flask app where I want to click a button on the home page, which will
On click, run Python script and route to my results.html. (which i have done)
Auto-fill certain fields on that page with results from a python script. (what i need help with)
The python script (parser.py) may take a 30-40 minutes to run, as its job is to start a test that takes about that long, then process and grab/parse the results. After that, some other fields will be filled in by the user, then the form on results.html is submitted to a database.
I hope i'm closer to my answer than I think, but where/how do I introduce my python into this and pass it into the form on results.html?
parser.py
import csv
import pandas as pd
import numpy as np
# Test data
body = pd.read_csv('path-to-test-data.csv', skiprows=11)
# Build dataframe of test info
frame = body['Frame Size']
loss = body['Loss Rate (Percent)']
speed = body['Tx Rate (L1) (Bit/s)']
grade = body['Result State']
lst = pd.concat([frame,loss,speed,grade], axis = 1)
selected_df = pd.DataFrame(data=lst)
selected_df.set_index('Frame Size')
# Select all 64b frame results
print(selected_df[np.isclose(selected_df['Frame Size'].values[:, None], [64],).any(axis=1)])
# Select all tests that fail
print(selected_df.loc[selected_df['Result State'] == 'FAIL'])
app.py:
import os
from flask import Flask, escape, request, redirect, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('index.html')
#app.route('/results/')
def about():
return render_template('results.html')
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OLT TESTER</title>
</head>
<body>
<div class="index">
Press This Button to Begin Testing
<button onclick=""></button>
</div>
</body>
</html>
results.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Results</title>
</head>
<body>
<div class="results">
Initialize Test
<form action="#.php" method="post">
Job Order: <input type="text" name="jobOrder"><br>
Serial Number: <input type="text" name="serialNo"><br>
Frame Size: <input type="text" name="jobOrder"><br> <!--Fill this field with Python output -->
Result State: <input type="text" name="serialNo"><br> <!--Fill this field with Python output -->
<input type="submit">
</form>
</div>
</body>
</html>
I am migrating several pages over to use our site's new template. These are legacy pages, though, so they need a couple extra global js files.
I was hoping to set a legacy flag in the child page views, and then have an if check in the master template, but this didn't seem to work.
Is there a better way to do this?
The ideal approach would mean I could simply declare the global legacy scripts in one place. I don't want to have to include them on every legacy child page, which is what we're doing now.
Parent template:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=.5"/>
<title>Title</title>
<link rel="stylesheet" href="/static/css/global.css"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<%block name="page_css" />
</head>
<body>
<!-- Body -->
<div class="bc-page-wrapper">
${self.body()}
</div>
<script type="text/javascript" src="/static/globals.js"></script>
% if legacy == 1:
<script type="text/javascript" src="/static/js/legacy.js"></script>
% endif
</body>
</html>
Legacy Page Inheriting Template:
<%
legacy = true
%>
<%inherit file="/global/ko_admin_template.html" />
<div class="legacy-container">
content here
</div>