Add loading view during process of the next view in Django - python

I want to add a loading page during the process, I tried all the solutions here in stackoverflow and different articales, but I'm really surprised that the solutions did not work for me, It's been 2 days and I still didn't find a solution.
I have two pages Home and datatable I want to add a loading page when i redirect from the home page to the datatable one. Please any help is highly appreciated.
this is my view.py :
def home_view(request):
context = {}
context ['form'] = Scraping()
return render(request,'home.html', context)
def datatable_view(request):
if request.method =='POST':
if form.is_valid():
return render(request,'datatable.html')

as i told you ajax calls should work i tried and its working. here's code
in local i had to set TimeOut fuction because response is quick so cant see loading effect.
Html:
<style>
.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #3498db; /* Blue */
border-radius: 50%;
width: 120px;
height: 120px;
animation: spin 2s linear infinite;
}
#keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
<div class="loader" style="display: none;" id="id_loader"></div>
Js click event:
function saveProfile() {
var postData = new FormData();
let token = localStorage.getItem("token");
postData.append('profile_id', $("#id_profile_id").val().trim());
postData.append('user_id', $("#id_user_id").val().trim());
postData.append('username', $("#id_username").val().trim());
postData.append('password', $("#id_password").val().trim());
postData.append('first_name', $("#id_first_name").val().trim());
postData.append('last_name', $("#id_last_name").val().trim());
postData.append('phone', $("#id_phone").val().trim());
postData.append('email', $("#id_email").val().trim());
postData.append('address', $("#id_address").val().trim());
$("#id_loader").show()
setTimeout(function () {
axios({
method: "post",
url: "http://192.168.1.249:7001/profile_save/",
data: postData,
headers: { "Content-Type": "application/json", 'X-CSRFToken': '{{ csrf_token }}', Authorization: `Bearer ${token}`, },
}).then(function (response) {
if (response.data && response.data.code == 1) {
$("#id_loader").hide();
swal("Successful!", response.data.msg, "success")
}
else if (response.data.code == 0) {
$("#id_loader").hide();
swal("Oops!", response.data.msg, "error")
}
})
}, 2000);
}

Related

Python - SocketIO Project - Msgs returned in HTML does not jump to end of DIV

I have a problem to solve with the scrollbar in html. I made a chat using socketio and the messages are being presented in a DIV inside an ASIDE. The problem is that when the scrollbar is mounted it leaves the thumb at the beginning. This impairs the navigability and reading of the chat. I would like it to stay in the end of messages.
I'm looking for routines or commands that after assembly, would scroll the bar to the end. Could ScrollTo() help me? If so, where to put it? On CSS? OnJavaScriptCode? On Server Side?
I would like your help. Thanks.
Below is the simplified routine to optimize the understanding of the problem.
app in python
from flask.app import Flask
from flask.templating import render_template
from flask_socketio import SocketIO, emit, send
app = Flask(_name_)
io = SocketIO(app)
messages = []
#app.route("/")
def home():
return render_template("chat.html")
#io.on('sendMessage')
def send_message_handler(msg):
print(msg)
messages.append(msg)
emit('getMessage', msg, broadcast=True)
#io.on('message')
def message_handler(msg):
send(messages)
if _name_ == "_main_":
io.run(app, debug=False, allow_unsafe_werkzeug=True)
Html code part
<aside>
<div class="chat"></div>
</aside>
CSS
main { display:flex;}
.chat {
display: flex;
flex-direction: column;
height:100%
margin-top: 2em;
float: left; /* Make this div as wide as its contents */
min-height: 96vh;
padding-left: 1em;
padding-top: 3em;
padding-right:1em;
border-right: 0.5px solid #898c91;
}
}
.chat span {
margin-bottom: 10px;
}
form {
margin-top: 10px;
}
aside {
overflow:hidden;
overflow-y:scroll;
height:300px;
width:45vh;
background: red;
scroll-snap-align: end;
}
Javascript code
window.onload = function() {
const socket = io('http://127.0.0.1:5000');
function addToChat(msg) {
const span = document.createElement("span");
const chat = document.querySelector(".chat");
span.innerHTML = `<strong>${msg.name}:</strong> ${msg.message}`;
chat.append(span);
}
socket.on('connect', () => {
socket.send('Usuário conectado ao socket!')
});
document.querySelector("form").addEventListener("submit", function(event) {
event.preventDefault();
socket.emit('sendMessage', {name: event.target[0].value, message: event.target[1].value})
event.target[0].value = "";
event.target[1].value = "";
})
socket.on('getMessage', (msg) => {
addToChat(msg)
})
socket.on('message', (msgs) => {
for(msg of msgs) {
addToChat(msg)
}
})
}
I found a solution.
socket.on('getMessage', (msg) => {
addToChat(msg)
const chatWindow = document.querySelector("#idchat");
chatWindow.scrollTop = chatWindow.scrollHeight;
})
That´s works fine! :)

Need suggestions : Django UserProfile geographic address to connect with others users

I hope you're well,
I'm looking for a plugin or a tutorial for :
a- allow my users to fill in their address on their profile. The best would be to have a map on which they can identify their address or like on the UberEats site.
b- to be able to find the closest users according to their address.
If you have any ideas, I'm interested,
I have already made the profile on Django, all I need is the address field.
The below code will do. You will need Javascript to play around a bit and set your form fields with the returned address.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 300px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<title>Places Searchbox</title>
<style>
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -33.8688, lng: 151.2195 },
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
map.addListener('click', function (locationdata) {
console.log(locationdata.latLng.lat());
console.log(locationdata.latLng.lng());
var myLatlng = new google.maps.LatLng(locationdata.latLng.lat(), locationdata.latLng.lng());
var myOptions = {
zoom: 13,
center: myLatlng
}
});
var geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, 'click', function (event) {
geocoder.geocode({
'latLng': event.latLng
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
alert(results[0].formatted_address);
}
}
});
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
console.log("lat: " + place.geometry.location.lat() + " lng: " + place.geometry.location.lng())
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
// [END region_getplaces]
}
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAkwr5rmzY9btU08sQlU9N0qfmo8YmE91Y&libraries=places&callback=initAutocomplete"
async defer></script>
</body>
</html>
You will need to add markers on map for each select. The code will console log the long and lat also, and return an alert with the address once you click it.
Credit goes to these two threads Link1 and Link2.
I managed to combine both codes and give results as you have mentioned.

Interacting with ChartJS from Flask

I am getting really confused on what to do here. I have a python script that does some cool things and then should display those cool things via some charts.
The way I've seen it's done is via Flask and ChartJS, but every website that I've seen uses it to display static content, which, of course, is not what I need.
I've tried doing this with this template:
<!doctype html>
<html>
<head>
<title>Line Chart</title>
<script src="/static/chartjs/Chart.min.js"></script>
<script src="/static/chartjs/utils.js"></script>
<style>
canvas{
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div style="width:75%;">
<canvas id="canvas"></canvas>
</div>
<br>
<br>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
<button id="removeData">Remove Data</button>
<script>
var MONTHS = [];
var config = {
type: 'line',
data: {
labels: ['1/05/19\n00:57', '1/05/19\n00:58', '1/05/19\n00:59', '1/05/19\n01:00', '1/05/19\n01:01', '1/05/19\n01:02', '1/05/19\n01:03'],
{{ dataset }}
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js Line Chart'
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);
};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
window.myLine.update();
});
var colorNames = Object.keys(window.chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = window.chartColors[colorName];
var newDataset = {
label: 'Dataset ' + config.data.datasets.length,
backgroundColor: newColor,
borderColor: newColor,
data: [],
fill: false
};
for (var index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
config.data.datasets.push(newDataset);
window.myLine.update();
});
document.getElementById('addData').addEventListener('click', function() {
if (config.data.datasets.length > 0) {
var month = MONTHS[1];
config.data.labels.push(month);
config.data.datasets.forEach(function(dataset) {
dataset.data.push(randomScalingFactor());
});
window.myLine.update();
}
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.splice(0, 1);
window.myLine.update();
});
document.getElementById('removeData').addEventListener('click', function() {
config.data.labels.splice(-1, 1); // remove the label first
config.data.datasets.forEach(function(dataset) {
dataset.data.pop();
});
window.myLine.update();
});
</script>
</body>
</html>
This contains a lot of unused stuff (it was downloaded directly from the chart.js samples) and slightly altered by me (see {{ dataset }})
And this is the python code I use to generate the dataset part:
def generate_dataset(self):
data = 'datasets: ['
for post_list_index, post in enumerate(self.post_list):
data = data + "{label: '" + post + "', backgroundColor: window.chartColors.red, borderColor: window.chartColors.red, data: ["
for index, history in enumerate(self.submissions_score_history):
score = history[post_list_index]
if index < len(self.submissions_score_history) - 1:
data = data + str(score) + ','
else:
data = data + str(score)
data = data + '],fill: false,}'
if post_list_index < len(self.post_list) - 1:
data = data + ','
else:
pass
data = data + ']'
return data
Now, unfortunately, this doesnt render anything. I'm pretty sure that this is due to the label: 'label'; being escaped to &#39label'.
I've searched about this issue and apparently this javascript injection thing I'm attempting to do has been removed because it represents a security vulnerability.
This project is quite literally just a dashboard for another small python project that will be used by me only, so I was trying to build something quickly and easily, but this is turning out to be quite troublesome :/

Pass Returned Data From Python to JavaScript?

As I'm developing one chat bot for booking bus tickets I get request from user manually and returned response based on user request from API I did almost but I have doubt while passing returned data from Python to JavaScript using my IP address. Please anyone help me.
Here is my py:
import requests,json
import requests, json
from flask import render_template
import os
import time
from flask import render_template, Flask, request
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot
# # import win32api
#
# win32api.MessageBox(0, 'hello', 'title')
app = Flask(__name__)
#app.route('/',methods=['GET','POST'])
def map():
return render_template("sara.html")
#app.route('/run',methods=['GET','POST'])
def main():
print("run")
url = 'http://webapi.i2space.co.in/Buses/Sources'
payload = {'some': 'data'}
headers = {'consumerkey': 'D0106432CD19C98E0E8267EDFE9E3DF0', 'consumersecret': '43DEC493EBAE756BF7A2312F55FE5132'}
r = requests.get(url, data=json.dumps(payload), headers=headers)
print(r.text)
# response_data = r.json()
response_data = json.loads(r.text)
# print(type(response_data))
# s=(response_data[0]['Name'])
# print(s)
sorceid=request.args.get('sid')
print(sorceid)
l=''
for a in response_data:
print("hello")
print(a)
print(a['Name'])
if (sorceid==a['Name']):
l=a['Id']
print(l)
break
else:
print("no")
# list={"iden":l}
# print(list)
return render_template("sara.html",l=l)
if __name__ == '__main__':
app.run(host='192.168.1.80')
Here is my JavaScript:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<h1> HERE COMES!!!</h1>
{{ l }}
<div class="w3-container w3-teal" align="center" style="width: 50%">
<span>Bus-Bot</span>
</div>
<div class="w3-container" align="center" style="width: 50%">
<div id="chatbox">
<p class="botText"> Bus-Bot:<span>Hi! I'm Bus-Bot.</span></p>
</div>
<div id="userInput">
<input id="textInput" type="text" name="msg">
<input id="buttonInput" type="submit" value="submit" >
</div>
<script>
function getBotResponse() {
var rawText = $("#textInput").val();
var userHtml = '<div id="Chatid" class="container">'+
'<p class="userText" >ME:<span>' + rawText + '</span></p>'+'</div>';
$("#chatbox").append(userHtml);
document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
$.get("run", { msg: rawText }).done(function (data) {
alert(data);
var sou=data.l;
alert(sou);
alert(lol);
var botHtml = '<div id="botcon" class="container darker">'+'<p class="botText">Bus-Bot:<span>' + sou + '</span></p>'+'</div>';
console.log(botHtml);
$("#botcon").append(botHtml);
document.getElementById('userInput').scrollIntoView({block: 'start', behavior: 'smooth'});
});
}
$("#textInput").keypress(function(e) {
if(e.which == 13) {
getBotResponse();
}
});$("#lolInput").keypress(function(e) {
if(e.which == 13) {
alert('weldone');
getBotResponse();
}
});
$("#buttonInput").click(function() {
getBotResponse();
})
</script>
<style>
.container {
border: 2px solid #dedede;
background-color: #f1f1f1;
border-radius: 5px;
padding: 10px;
margin: 10px 0;
}
/* Darker chat container */
.darker {
border-color: #ccc;
background-color: #ddd;
}
/* Clear floats */
.container::after {
content: "";
clear: both;
display: table;
}
/* Style images */
.container img {
float: left;
max-width: 60px;
width: 100%;
margin-right: 20px;
border-radius: 50%;
}
/* Style the right image */
.container img.right {
float: right;
margin-left: 20px;
margin-right:0;
}
/* Style time text */
.time-right {
float: right;
color: #aaa;
}
/* Style time text */
.time-left {
float: left;
color: #999;
}
</style>
</div>
</div>
</body>
</html>
From Python I returned response using variable name "l" but I don't know how to pass this variable to JavaScript I want to get my response below to this line
var botHtml = '<div id="botcon" class="container darker">'+'<p class="botText">Bus-Bot:<span>' + sou + '</span></p>'+'</div>';
The render_template function from Flask doesn't pass any variable from one language to the other. It just replaces strings inside the html-template that it finds with a variable that you handover to it. With
return render_template("sara.html",l=l)
you are telling the program to take the sara.html template and insert your variable l anywhere where it finds {{ l }} in the template. You should see it in the actual HTML that you are sending to the client. because you are inserting it under your heading:
<h1> HERE COMES!!!</h1>
{{ l }}
It is really more helpful if you are using it to render pure HTML and not JavaScript. Of cause you can also replace things inside your JavaScript but that is really not a sensible way to do client-server communication. If you want communication between your client and server you should think about a different architecture.
Doing the get call
url = 'http://webapi.i2space.co.in/Buses/Sources'
payload = {'some': 'data'}
headers = {'consumerkey': 'D0106432CD19C98E0E8267EDFE9E3DF0', 'consumersecret': '43DEC493EBAE756BF7A2312F55FE5132'}
r = requests.get(url, data=json.dumps(payload), headers=headers)
inside your server is probably better kept in your client-side Javascript.

OpenLayers Geolocation in PyQt 5.9

I've implemented a Website with a geolocation function and Button.
This Webpage gets displayed fine in a QwebEngineView (OSM Map too).
The Webpage is loaded
def __init__(self, parent=None):
super(MainGUI, self).__init__(parent)
self.ui = uic.loadUi("GPS.ui", self)
self.ui.w3View.load(QtCore.QUrl('file:///Map.html'))
All native OpenLayers Buttons (Zoom IN and OUT) are working fine.
I created a new custom button to display my geolocation on the OpenLayers Map.
This is the function im using to geolocate me:
var handleGeolocation = function() {
var coordinates;
var geolocation = new ol.Geolocation({
projection: view.getProjection(),
tracking: true
});
// handle geolocation error.
geolocation.on('error', function (error) {
var info = document.getElementById('info');
info.innerHTML = error.message;
info.style.display = '';
});
var accuracyFeature = new ol.Feature();
geolocation.on('change:accuracyGeometry', function () {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
});
var positionFeature = new ol.Feature();
positionFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
}));
geolocation.once('change:position', function () {
coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ?
new ol.geom.Point(coordinates) : null);
map.getView().setCenter(coordinates);
map.getView().setZoom(17);
});
new ol.layer.Vector({
map: map,
source: new ol.source.Vector({
features: [accuracyFeature, positionFeature]
})
});
}
I created the Button with the help from here.
the whole Webpage looks like this:
<!DOCTYPE html>
<html>
<head>
<title>Accessible Map</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.2.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.2.0/build/ol-debug.js"></script>
<style>
a.skiplink {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
padding: 0;
border: 0;
height: 1px;
width: 1px;
overflow: hidden;
}
a.skiplink:focus {
clip: auto;
height: auto;
width: auto;
background-color: #fff;
padding: 0.3em;
}
#map:focus {
outline: #4A74A8 solid 0.15em;
}
map{
max-width: 760 px;
max-height: 50 px;
}
.geoButton {
top: 80px;
left: .5em;
}
</style>
</head>
<body>
<div id="map" class="map" tabindex="0"></div>
<script>
window.app = {};
var app = window.app;
view = new ol.View({
center: [0, 0],
zoom: 2
});
app.getLocation = function(opt_options) {
var options = opt_options || {};
var geoButton = document.createElement('button');
geoButton.innerHTML = 'L';
var handleGeolocation = function() {
/* var isMobile = {
Android: function () {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function () {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function () {
return navigator.userAgent.match(/iPhone|iPod|iPad/i);
},
Opera: function () {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function () {
return navigator.userAgent.match(/IEMobile/i);
},
any: function () {
return ((isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()));
}
};
if (isMobile.any()){
geolocation.setTrackingOptions(enableHighAccuracy );
} */
var coordinates;
var geolocation = new ol.Geolocation({
projection: view.getProjection(),
tracking: true
});
// handle geolocation error.
geolocation.on('error', function (error) {
var info = document.getElementById('info');
info.innerHTML = error.message;
info.style.display = '';
});
var accuracyFeature = new ol.Feature();
geolocation.on('change:accuracyGeometry', function () {
accuracyFeature.setGeometry(geolocation.getAccuracyGeometry());
});
var positionFeature = new ol.Feature();
positionFeature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: 6,
fill: new ol.style.Fill({
color: '#3399CC'
}),
stroke: new ol.style.Stroke({
color: '#fff',
width: 2
})
})
}));
geolocation.once('change:position', function () {
coordinates = geolocation.getPosition();
positionFeature.setGeometry(coordinates ?
new ol.geom.Point(coordinates) : null);
map.getView().setCenter(coordinates);
map.getView().setZoom(17);
});
new ol.layer.Vector({
map: map,
source: new ol.source.Vector({
features: [accuracyFeature, positionFeature]
})
});
}
geoButton.addEventListener('click', handleGeolocation, false);
geoButton.addEventListener('touchstart', handleGeolocation, false);
var element = document.createElement('div');
element.className = 'ol-unselectable ol-control geoButton';
element.appendChild(geoButton);
ol.control.Control.call(this, {
element: element,
target: options.target
});
};
ol.inherits(app.getLocation, ol.control.Control);
//Standard Initialisierung
// Geolocation function
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}).extend([new app.getLocation()]),
view: view
});
//Display Input Datastream
</script>
</body>
</html>
Inside a normal browser it's working fine but not inside my PyQt app.
After clicking the custom Button nothing happens.
What am i doing wrong or is not possible?
The main problem is to enable the permissions, if you run in a browser like Firefox, Chrome, etc. will show you a popup asking you to accept or not the GeoLocation permission.
In this case it must be enabled by code, for this the QWebEnginePage emits a signal every time authorization is required, it does this through the signal featurePermissionRequested, we connect it to some slot and we enable the permission with the function setFeaturePermission().
self.ui.w3View..page().featurePermissionRequested.connect(self.onFeaturePermissionRequested)
def onFeaturePermissionRequested(self, securityOrigin, feature):
self.sender().setFeaturePermission(securityOrigin,
QWebEnginePage.Geolocation,
QWebEnginePage.PermissionGrantedByUser)
Note: On Linux I still experience problems with the Geoclue provider, the error message reads as follows:
Failed to set Geoclue positioning requirements. Geoclue error:
org.qtproject.QtDBus.Error.InvalidObjectPath
Adding the following lines solved my Problems:
self.ui.w3View.page().featurePermissionRequested.connect(self.permissionRequested)
def permissionRequested(self, frame, feature):
self.ui.w3View.page().setFeaturePermission(frame, feature, QtWebEngineWidgets.QWebEnginePage.PermissionGrantedByUser)
Found it in this post and editing it to PyQt 5.9.

Categories

Resources