I am using django to create a webpage and this is the first time I am doing so. I am trying to fetch the value of a variable from .py file at an interval of 5 seconds. Below is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Like Post App</title>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class = "display-3 color-red"><center>DataFlair AJAX Tutorial<br>Post APP</center></div>
{% for post in posts %}
<div class = 'container jumbotron'>
<h3 class="display-5">{{ forloop.counter }}. {{ post.post_heading }}</h3>
<p class="lead">{{ post.post_text }} </p>
<p>
<div type="text/css" class = "container">Author : {{ post.post_author }}</div>
<a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" data-catid="{{ post.id }}">Like({{ post.like_ref.counter }})</a> </p> <p id="message{{post.id}}">
</p>
</div>
{% endfor %}
<script type="text/javascript">
setInterval(function() {
getvalue(); // Do something every 5 seconds
}, 5000);
getvalue();
function getvalue(){
var id;
id = $(this).attr("data-catid");
$.ajax(
{
type:"GET",
url: "like",
data:{
post_id: id
},
success: function( data )
{
$( '#like'+ id ).text("Like(" + data +")");
var i=parseInt(data);
console.log("Value= "+i);
}
}
)
}
</script>
</body>
</html>
Below is the views.py code:
import json
from django.shortcuts import render
from .models import Post, Like
from django.http import HttpResponse
# Create your views here.
#DataFlair #AJAX_tutorial
def index(request):
posts = Post.objects.all()
return render(request, 'post/index.html', { 'posts': posts })
def like(request):
if request.method == 'GET':
post_id = request.GET['post_id']
likedpost = Post.objects.get(id = post_id )
m = Like.objects.filter( post=likedpost ).first()
m.counter +=1
m.save()
value1= int(m.counter)
#data1= {'cmd': 'success', 'ctr': str(m.counter) }
return HttpResponse(value1)
#return HttpResponse(json.dumps(data1))
else:
return HttpResponse("unsuccesful")
I keep getting the following errors:
1) GET http://localhost:8000/ajax/like/ 500 (Internal Server Error)
2) GET http://localhost:8000/favicon.ico 404 (Not Found)
Please help.
I believe:
id = $(this).attr("data-catid");
is not pointing to the button... maybe you should try:
id = $(".likebutton").attr("data-catid");
Related
`#views.route('/flight.html',methods = ['GET','POST'])
def flight():
if request.method == 'POST':
global no_of_passenger
no_of_passengers = request.form.get('no_of_passengers')`
In the above view, I'm getting the passenger count from an earlier html page which I'm using later. I need to get the input from the user as many times as the no_of_passengers.
`#views.route('/passengers.html',methods = ['GET','POST'])
def passenger():
if request.method == 'POST':
return render_template('passengers.html')
return render_template('passengers.html')
#views.route('/passengersinfo.html',methods = ['GET','POST'])
def passenger_information():
passengercount = no_of_passengers
passengercount = int(passengercount)
print(passengercount)
if request.method == 'POST':
for i in range(0,passengercount):
passenger_info = {}
passenger_info['passengername'] = request.form.get('Passenger_Name')
passenger_info['Street'] = request.form.get('Street')
passenger_info['City'] = request.form.get('City')
passenger_info['State'] = request.form.get('State')
passenger_info['ZipCode'] = request.form.get('ZipCode')
return redirect(url_for("views.passenger"))
return render_template('passengersinfo.html')`
In this view I'm trying to run the form as per the user input using a for loop.
The below attached code is the HTML form which is used to get the user form data.
`{% extends 'base.html'%}
{% block title %}Passenger Information Page{% endblock %}
{% block content %}
<form id="Form1" action = 'passengersinfo.html' method = 'POST'>
<div>
<label for ='Passenger_Name' >Passenger Name</label>
<input type = 'text' name = 'Passenger_Name' id='Passenger_Name' id="Form1">
<br>
<label for ='Street' >Street</label>
<input type = 'text' name = 'Street' id='Street' id="Form1">
<br>
<label for ='City' >City</label>
<input type = 'text' name = 'City' id='City' id="Form1">
<br>
<label for ='State' >State</label>
<input type = 'text' name = 'State' id='State' id="Form1">
<br>
<label for ='Zip' >Zip Code</label>
<input type = 'text' name = 'Zip' id='Zip' id="Form1">
</div>
<button type = 'submit' id="Form1" >Next</button>
</form>
{%endblock%}
`
An easy way to implement your requirements is to use Flask-WTF.
Using a FieldList and a FormField, it is possible to create a list of a predefined form.
In this way you create a form for your address details and, depending on the required number, you duplicate this. In addition, you can validate the entries made.
If you only want to display one nested form at a time, you can use JavaScript to navigate forward or back.
The following example uses the session to avoid using global variables and stay as close to your defaults as possible.
Flask
from flask import (
Flask,
redirect,
render_template,
request,
session,
url_for
)
from flask_wtf import FlaskForm, Form
from wtforms import (
FieldList,
FormField,
IntegerField,
StringField,
SubmitField
)
from wtforms.validators import (
InputRequired,
NumberRange
)
app = Flask(__name__)
app.secret_key = 'your secret here'
class PassengersForm(FlaskForm):
passenger_count = IntegerField('Ticket Count',
validators=[NumberRange(min=1)]
)
submit = SubmitField('Next')
class PassengerForm(Form):
name = StringField('Name',
validators=[InputRequired()]
)
street = StringField('Street/No')
city = StringField('City')
state = StringField('State')
zipcode = StringField('Zip')
class PassengerDetailsForm(FlaskForm):
passengers = FieldList(FormField(PassengerForm))
submit = SubmitField()
#app.route('/passengers', methods=['GET', 'POST'])
def passengers():
form = PassengersForm(request.form, data={'passenger_count': 1})
if form.validate_on_submit():
session['count'] = form.passenger_count.data
return redirect(url_for('.passengers_info'))
return render_template('passengers.html', **locals())
#app.route('/passengers-info', methods=['GET', 'POST'])
def passengers_info():
form = PassengerDetailsForm(request.form)
form.passengers.min_entries = max(1, int(session.get('count', 1)))
while len(form.passengers.entries) < form.passengers.min_entries:
form.passengers.append_entry()
if form.validate_on_submit():
for passenger in form.passengers.data:
print(passenger)
return redirect(url_for('.passengers'))
return render_template('passengers_info.html', **locals())
HTML (./templates/passengers.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Passengers</title>
</head>
<body>
<form method="post">
{{ form.csrf_token }}
<div>
{{ form.passenger_count.label() }}
{{ form.passenger_count() }}
{% if form.passenger_count.errors -%}
<ul>
{% for error in form.passenger_count.errors -%}
<li>{{ error }}</li>
{% endfor -%}
</ul>
{% endif -%}
</div>
{{ form.submit }}
</form>
</body>
</html>
HTML (./templates/passengers_info.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Passenger Informations</title>
<style type="text/css">
.step {
display: none;
}
.step.active {
display: block;
}
</style>
</head>
<body>
<form method="post">
{{ form.csrf_token }}
{% for subform in form.passengers -%}
<div class="step {%if loop.first %}active{% endif %}" id="step-{{loop.index0}}">
{% for field in subform -%}
<div>
{{ field.label() }}
{{ field() }}
{% if field.errors -%}
<ul>
{% for error in field.errors -%}
<li>{{ error }}</li>
{% endfor -%}
</ul>
{% endif -%}
</div>
{% endfor -%}
{%if not loop.first %}
<button type="button" class="btn-prev">Prev</button>
{% endif %}
{%if not loop.last %}
<button type="button" class="btn-next">Next</button>
{% else %}
{{ form.submit() }}
{% endif %}
</div>
{% endfor -%}
</form>
<script type="text/javascript">
(function() {
let step = 0;
const btns_next = document.querySelectorAll('.btn-next');
btns_next.forEach(btn => {
btn.addEventListener('click', evt => {
[`step-${step}`, `step-${++step}`].forEach(sel => {
const elem = document.getElementById(sel);
elem && elem.classList.toggle('active');
});
});
});
const btns_prev = document.querySelectorAll('.btn-prev');
btns_prev.forEach(btn => {
btn.addEventListener('click', function(evt) {
[`step-${step}`, `step-${--step}`].forEach(sel => {
const elem = document.getElementById(sel);
elem && elem.classList.toggle('active');
});
});
});
})();
</script>
</body>
</html>
I try to upload two forms with one submit button.
A user can select a pdf file and a excel file. And then uploading both files. And then the contents of both are returned.
So I try to upload both files with one submit button.
But the two selected file options are not visible for uploading the files.
So I have the template like this:
{% extends 'base.html' %} {% load static %} {% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Create a Profile</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="{% static 'main/css/custom-style.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'main/css/bootstrap.css' %}" />
</head>
<body>
<div class="container center">
<span class="form-inline" role="form">
<div class="inline-div">
<form class="form-inline" action="/controlepunt140" method="POST" enctype="multipart/form-data">
<div class="d-grid gap-3">
<div class="form-group">
{% csrf_token %}
{{ form.0.as_p }}
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
</div>
<div class="form-outline">
<div class="form-group">
<textarea class="inline-txtarea form-control" id="content" cols="70" rows="25">
{{content}}</textarea>
</div>
</div>
</div>
<div class="d-grid gap-3">
<div class="form-group">
{{ form.1.as_p }}
</div>
<div class="form-outline">
<div class="form-group">
<textarea class="inline-txtarea form-control" id="content" cols="70" rows="25">
{{conten_excel}}</textarea>
</div>
</div>
</div>
</form>
</div>
</span>
</div>
</body>
</html>
{% endblock content %}
and the views.py:
class ReadingFile(View):
def get(self, *args, **kwargs):
return render(self.request, "main/controle_punt140.html", {
"form1": UploadFileForm(),
"form2": ExcelForm()
})
def post(self, *args, **kwargs):
filter_text = FilterText()
types_of_encoding = ["utf8", "cp1252"]
form1 = UploadFileForm(
self.request.POST, self.request.FILES, prefix="form1")
form2 = ExcelForm(self.request.FILES,
self.request.FILES, prefix="form2")
content = ''
content_excel = ''
if form1.is_valid() and form2.is_valid() and self.request.POST:
uploadfile = UploadFile(image=self.request.FILES["upload_file"])
excel_file = self.request.FILES["upload_file"]
uploadfile.save()
for encoding_type in types_of_encoding:
with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
if uploadfile.image.path.endswith('.pdf'):
content = filter_text.show_extracted_data_from_file(
uploadfile.image.path)
else:
content = f.read()
if uploadfile.image.path.endswith('xlsx'):
wb = openpyxl.load_workbook(excel_file)
worksheet = wb['Sheet1']
print(worksheet)
excel_data = list()
for row in worksheet.iter_rows():
row_data = list()
for cell in row:
row_data.append(str(cell.value))
excel_data.append(row_data)
print(excel_data)
content_excel = excel_data
else:
content_excel = f.read()
return render(self.request, "main/controle_punt140.html", {
'form1': ExcelForm(),
'form2': UploadFileForm(),
"content": [content, content_excel]
})
# I've adjusted the indent here to what I think it should be.
return render(self.request, "main/controle_punt140.html", {
"form1": form1,
"form2": form2,
})
and forms.py:
class UploadFileForm(forms.Form):
upload_file = forms.FileField(required=False)
class ExcelForm(forms.Form):
upload_file = forms.FileField(required=False)
urls.py:
urlpatterns = [
path('', views.starting_page, name='starting_page'),
path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140'),
]
The variable name used in the template is the key of the dictionary, not the value. The value is what is inserted into the template when django renders the page.
You have {{form1.as__p}} in your template, but you send "form": [form1, form2] as your context, so the variable in the template should be {{ form.0.as_p }} and {{ form.1.as_p }}. I haven't tested this, but if it doesn't work, you could just send the two forms separately like:
from django.shortcuts import redirect
class ReadingFile(View):
def get(self, *args, **kwargs):
return render(self.request, "main/controle_punt140.html", {
"form1": UploadFileForm(),
"form2": ExcelForm()
})
def post(self, *args, **kwargs):
filter_text = FilterText()
types_of_encoding = ["utf8", "cp1252"]
form1 = UploadFileForm(self.request.POST, self.request.FILES, prefix="form1")
form2 = ExcelForm(self.request.FILES, self.request.FILES, prefix="form2")
content = ''
content_excel = ''
if form1.is_valid() and form2.is_valid() and self.request.POST:
uploadfile = UploadFile(image=self.request.FILES["upload_file"])
excel_file = self.request.FILES["upload_file"]
uploadfile.save()
for encoding_type in types_of_encoding:
with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
if uploadfile.image.path.endswith('.pdf'):
content = filter_text.show_extracted_data_from_file(
uploadfile.image.path)
else:
content = f.read()
if uploadfile.image.path.endswith('xlsx'):
#Uploading excel form:
#this is just logic.
pass
else:
content_excel = f.read()
# You probably should do a redirect after the form is
# submitted, rather than render the page.
return redirect('main:controlepunt140')
# return render(self.request, "main/controle_punt140.html", {
'form1': ExcelForm(),
'form2': UploadFileForm(),
"content": [content, content_excel]
})
# I've adjusted the indent here to what I think it should be.
return render(self.request, "main/controle_punt140.html", {
"form1": form1,
"form2": form2,
})
You probable should also change to a redirect after the form is submitted and saved successfully. Check out Post/Redirect/Get and/or rendering content after a succesful post request.
Edit
Changed template to use {{ form.0.as_p }} as indicated by #nigel239
You can redirect to the same page where the form was submitted, so if the user hits the refresh button on their browser for some reason, you will not get an alert box asking the user to resend the form.
I want to send {{order.id}}, but getting error like pictuce in bellow, please helping me to solve problem
Image Error
Views.py:
def Detail_pem(request, idor):
print(idor)
return render(request, 'store/detail.html' )
pemby.html:
<!-- <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> -->
<button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> -->
<script>
var id_order = document.getElementsByClassName('id_order')
for (i = 0; i < id_order.length; i++) {
id_order[i].addEventListener('click', function(){
var orid = this.dataset.product
var ornm = this.dataset.act
console.log('orid :', orid)
console.log('ornm :', ornm)
window.location.href = "{% url 'Detail_pem' %}"
})
}
urls.py:
path('Detail_pem/<idor>', Detail_pem, name='Detail_pem'),
You are redirecting through
window.location.href = "{% url 'Detail_pem' %}" without a variable.
But in your urls.py you are passing idor variable.
It should be: window.location.href = "{% url 'Detail_pem' order.id } %}".
And your urls.py change to this:
int:id
#if you are passing integer
path('Detail_pem/<int:id>', Detail_pem, name='Detail_pem'),
#or if you are passing string
path('Detail_pem/<str:id>', Detail_pem, name='Detail_pem'),
I am using full calendar in my in my Django project and I was wondering how I would get the model data to load as an event within the calendar. The issue is whenever I try to load the template into my code it loads up a white page with text in JSON format.
I was wondering if it was possible to get by this.
This is how my model looks like:
class CalenderEvent(models.Model):
event_name = models.CharField(max_length = 30)
start_date = models.DateTimeField(null=True,blank=True)
end_date = models.DateTimeField(null=True,blank=True)
event_description = models.TextField()
def __str__(self):
return self.event_name
This is how my view looks like:
def calender(request):
events = CalenderEvent.objects.all()
if request.method == 'GET':
form = ContactToAddEventForm()
event_arr = []
for i in events:
event_sub_arr = {}
event_sub_arr['title'] = i.event_name
start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d")
event_sub_arr['start'] = start_date
event_sub_arr['end'] = end_date
event_arr.append(event_sub_arr)
return HttpResponse(json.dumps(event_arr))
context = {
"events" : events
}
return render(request, 'calender.htm', {'form': form}, context)
This is how my template looks like:
<link rel="stylesheet" href="{% static "fullcalender/daygrid/main.css" %}" >
<link rel="stylesheet" href="{% static "fullcalender/timegrid/main.css" %}" >
<link rel="stylesheet" href="{% static "fullcalender/core/main.css" %}" >
<script rel="stylesheet" href="{% static "fullcalender/core/main.js" %}" ></script>
<script src="{% static "fullcalender/core/main.js" %}"></script>
<script src="{% static "fullcalender/daygrid/main.js" %}"></script>
<script src="{% static "fullcalender/timegrid/main.js" %}"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'timeGrid' ],
defaultView: 'timeGridWeek',
events: [
{% for i in events %}
{
title: "{{ i.event_name}}",
start: '{{ i.start_date|date:"Y-m-d" }}',
end: '{{ i.end_date|date:"Y-m-d" }}',
},
{% endfor %}
]
});
calendar.render();
});
</script>
<section>
<div class="container">
<div id = "calendar"></div>
</div>
</section>
I was looking at this stack overflow answer:
FullCalendar in Django
I have a small flask app I am using it to:
Make an HTML page with a leaflet map
Take user input from the HTML page...
Run calculations on that input using certain python modules
Return those variable to JS functions in the page to populate the map
I cannot get ANYTHING but lat and lng to return into my HTML {{}} flask variables.
Here is my HTML page:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 != None and lng1 != None %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
Here is my Flask Python code:
from flask import Flask, render_template, request, flash, redirect, url_for,jsonify
from forms import RegistrationForm
import json
import osmnx as ox
import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import json_graph
import pandas as pd
import mplleaflet
app = Flask(__name__)
app.config.update(dict(
SECRET_KEY="powerful secretkey",
WTF_CSRF_SECRET_KEY="a csrf secret key"
))
#app.route('/')
def my_form():
return render_template('map.html')
#app.route('/', methods=['GET', 'POST'])
def my_form_post():
lat = (request.form['lat'])
lng = (request.form['lng'])
lat = lat
lng = lng
point = (lat,lng)
G = ox.core.graph_from_point(point, distance = 500, network_type='walk')
fig, ax = ox.plot_graph(G)
GJ = mplleaflet.fig_to_geojson(fig=ax.figure)
#return lat, ",", lng
return render_template('map.html', lat1=lat, lng1=lng, GeJ=GJ, point="test_string")`
if __name__ == "__main__":
app.run(host='0.0.0.0',port=5000,debug=True)
The Flask app is working fine so the file structure is not a concern. I just cannot get any other variables to return into my HTML. I even tried making little string dummy variables other that the real ones. No Dice.
Thanks
You could try using the builtin none value http://jinja.pocoo.org/docs/templates/#none
Then do something like:
{% if lat1 is not none and lng1 is not none %}
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 is not Null and lng1 is not Null %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
It would help if you provided an example of what exactly happens when you pass all the values.
Otherwise, what according to me, could be causing the problem is that the 'Null' object in python is the singleton None. The best way to check things for "Noneness" is to use is not None or better still, something as simple as:
{%if lat%} {{lat}} {% endif %}
Also, can't you assign GeJ to the var GeJ within the div instead of putting a line of JS in an abrupt manner up there?
P.S. I wanted to add this as a comment, but don't have enough reputation. Apologies.