Datalist from python list - javascript

I am trying to generate a datalist on my website that comes from a list on python.
My html file is like this:
<!DOCTYPE html>
<html>
<body>
<form>
<input list="hschools" name="hschool">
<datalist id="hschools">
{% for elem in hsch %}
<option value= {{elem}}>
{% endfor %}
</datalist>
<input type="submit">
</form>
</body>
</html>
And is saved in trying.html
My main.py file is:
from flask import Flask,render_template
app=Flask(__name__)
#app.route("/")
def index():
hsch=["a","b","c"]
return render_template("trying.html")
if __name__=="main":
app.run()
I then try to run the web-app and I do not get anything. Can you see my error?
Maybe I am not running it correctly... Thanks!

render_template needs hsch to be passed:
return render_template("trying.html", hsch=hsch)

Related

How can I get a User input and add it in a url and open the url in a new tab?

I know nothing about it.
I need to make a simple website.
I will take an input from user.
Suppose the input is 'LOL'
Then I need to open a new tab with this url - "https://www.help.me/LOL"
#Help me Please
You can do it by using django forms
In your project directory in views.py file you can use this code
from django import forms
from django.http import HttpResponseRedirect
class inputform(forms.Form):
inputfield = forms.CharField(label="Input")
def index(request):
if request.method == "POST":
x = inputform(request.POST)
if x.is_valid():
y = x.cleaned_data["inputfield"]
return
HttpResponseRedirect(f"https://www.help.me/{y}")
return render(request, "index.html", { "form":
inputform() }
In HTML, you can write the following code to represent the Input Field in HTML page
in index.html;
<!DOCTYPE html>
<html lang="en">
<head>
<title> xyz </title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
</form>
</body>
</html>
By this you will get your desired results

How to output $.get() method JQuery with Flask

I could not output the data created in Flask to JQuery in a Html page.
I am testing $.get() method in JQuery with Flask. The task is to return a String to a Html page and display it as paragraph. But the result cannot be displayed. Can someone shed a light on this issue. Thanks!
Here is the code in Flask
from flask import request, jsonify, Flask
app = Flask(__name__)
#app.route('/', methods=["GET"])
#app.route('/hello', methods=["GET"])
def hello():
return jsonify('<h1>Hello Flask !!!</h1>')
Here is the html code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Events </title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function()
{
$("#btnGet").click(function()
{
//$.get('https://httpbin.org/get',
$.get('http://localhost:5000/hello',
function(data)
{
$("#getInfo").text(data)
});
});
});
</script>
</head>
<body>
<button id="btnGet">Click to Get Info </button>
<p id="getInfo"></p>
</body>
</html>
As new to web programming, after hours trial and error, finally found out that I am not placing the html under static folder and run it in Eclipse Environment. After open it up in http://localhost:5000/static/test.html then it works as expected.

Code dynamic dropdown using Python, sqlite3, HTML and JavaScript

I want to fetch userdata from sqlite DB table and list them as a dropdown list in my HTML code. I am new to Python. I tried writing a code, but it failed. list_fetched is my users list that I fetched from db table.
#app.route('/trail', methods=['POST', 'GET'])
def index():
list_tested = db_dropdown()
return render_template("try.html", trail1=list_fetchted)
return "hi"
try.html:
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trail1|tojson }};
function clicked()
{
alert("trail1[0]")
}
</script>
</body>
</html>
No value is getting displayed.
I would recommend looking at the quick start guide for Flask, it may give some advice on your problem and help with your future learning.
(https://flask.palletsprojects.com/en/1.0.x/quickstart/)
I have a solution for your issue (I have removed any sqlite access but sure you can put that in):
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def hello():
return render_template("try.html", trial1=['1', '2'])
Then your try.html file needs to be placed in /templates/try.html in your project directory. By default this is where Flask references templates.
<html>
<head>
</head>
<body>
<p>Hello World</p>
<button type="submit" onclick="clicked()">Submit</button>
<script>
var trail1 = {{ trial1|tojson }};
function clicked()
{
alert(trail1[0])
}
</script>
</body>
</html>
Enjoy learning python :)

Running python file on HTML button click (Django)

Relevant information:
1) First post on here, go easy.
2) I'm a noob.
3) Trying to learn python/Django.
What I'm trying to do:
1) Create an english -> pig latin translator (written in python) and have it work in browser.
How I want it to work:
1) User clicks "translate" button, which then uses my existing python function to translate their input.
2) The translation is then displayed below the input.
What I've done so far:
1) Created .py file that successfully translates english -> pig latin in the console.
def pigLatin(sentence):
translation = " "
for word in sentence.split():
if word[0] in "aeiou":
translation += word + "yay "
if word[0] and word[1] not in "aeiou":
translation += word[2:] + word[0:2] + "ay"
print("hai")
else:
translation += word[1:] + word[0] + "ay "
return translation
sentence = input("Enter word/sentence you want translated to pig latin below: ")
print(pigLatin(sentence))
2) Used Jinja/added some HTML and bootstrap (please see below)
What it looks like in browser
3) Created a Django project, and installed my pig latin app, my folders are structured as so:
--mysite
|
|--pigLatinApp
|----templates
|------pigLatinApp
|--------home.html
|--------header.html
3) Attempted to use Ajax to get my button working, my HTML files and views.py are as follows:
header.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Pig Latin Translator</title>
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css">
</head>
<body class="body">
<section id="translatorSection">
<!------------------Log Sum Container-------------------------->
<div class="container" id="translatorContainer">
{% block content %}
{% endblock %}
</div>
</section>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js">
</script>
</body>
</html>
home.html
{% extends "pigLatinApp/header.html" %}
{% block content %}
<div class="row">
<div class="col-md-6">
<form>
<h3>Pig Latin Translator</h3>
<p>Enter below what you want translated!</p>
<input type="string" class="form-control" placeholder="Type what you want translated here!" id="inputSumA">
<button id="translateToPig" class="btn btn-success form-control">Translate</button>
<div id="displayTranslation">
<p>{{ output }}</p>
</div>
</form>
</div>
</div>
<script>
$("#translateToPig").click(function() {
$.get("/output/", function(data) {
$("#displayTranslation").html(data);
}, "html");
});
</script>
{% endblock %}
views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return render(request, 'pigLatinApp/home.html')
def output(request):
if request.is_ajax():
py_obj = pigLatinTranslator.test_code(10)
return render(request, 'pigLatinApp/output.html', {'output': py_obj.a})
What actually happens when I click the button:
1) Nothing... The page seems to refresh.
Any and all help would be appreciated, cheers!
Here:
<script>
$("#translateToPig").click(function() {
$.get("/output/", function(data) {
$("#displayTranslation").html(data);
}, "html");
});
</script>
Your click event handler doesn't prevent the event's default action, so your form is submitted by the browser. Since your form has no 'action' attribute it's submitted to the current url, so the index view is called and the page is reloaded.
You can prevent this by calling preventDefault() on the event ie:
<script>
$("#translateToPig").click(function(evt) {
evt.preventDefault(); # prevents posting the form
evt.stopPropagation(); # make sure it doesn't bubble up
$.get("/output/", function(data) {
$("#displayTranslation").html(data);
}, "html");
});
</script>
Now there are a couple things that could be improved in your code but that's another topic. At least I think you should first try to get something working without ajax, so you learn the whole request/response cycle stuff, working with GET and POST, using django forms etc.
I recommend trying a normal request i.e. not ajax and also creating a form.py where you can create a form class for the search. In your views import the pig latin translator function and call it in your output function.

How to get query string value in client side after page upload using Django and Python

I need to fetch the the query string value from URL on the client side and that URL is passed from Django template. I am explaining my code below.
base.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{% load static %}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<header>
<h1>Nuclear Reactor</h1>
{% if count > 0 %}
<b>Hi, {{ user.username }}</b>
Home
View Reactor status
logout
{% else %}
login / signup
{% endif %}
<hr>
</header>
<main>
{% block content %}
{% endblock %}
</main>
</body>
</html>
Here I am passing some query string value for home.html loading.
home.html:
{% extends 'base.html' %}
{% block content %}
<center><h1>Welcome</h1>
<p>This App allow to control the life cycle of the Nuclear Reactor and Retrive the status report </p>
<p>Status reportControl panel</p>
</center>
<script type="text/javascript">
window.onload=function(){
}
</script>
{% endblock %}
I need to fetch the query string using JavaScript when the home page rendered.
If you want to do this in the client side, I think you can use javascript location object:
<script type="text/javascript">
window.onload=function(){
querystring = location.search;
// do something
}
</script>
Otherwise, you can get the parameters from the request in the server side (in the view) and inject the object to the template.

Categories

Resources