Is it possible to save the javascript html5 geolocation latitude and longitude to the django admin when user uses the geolocation website. The web page goal is to save the user's longitude and latitude values so that the data can be accessed later on when user signs in again.
I found a similar question being asked in stackoverflow years ago but there hasn't been any answer. The link is : Save JavaScript GeoLocation data to Django admin page
It would be great if there this an answer based on this code link.
Another option I read about is to create a html form and set the form to be autopopulated by jQuery from data produced by the javascript html5 geolocation. Again this is quite complicated for a beginner like me.
I would appreciate any bit of help whether by code, tutorial, blog post, examples or links. I don't expect all the programming code to be provided (although I do learn better from examples) but it would help if there are some material/example I could go to, to implement my programming tasks. Thank you.
I am currently up to here with my progress but still am unable to post the latitude and longitude to the django admin page:
code is as following:
The structure of the django project is as follows:
-ajax
- __pycache__
- migrations
- __pycache__
0001_initial.py
__init__.py
- static
- css
- bootstrap.css
- fonts
- js
- script.js
- templates
- ajax
- base.html
- index.html
- __init__.py
- admin.py
- apps.py
- models.py
- tests.py
- urls.py
- views.py
-server
- __pycache__
- __init__.py
- settings.py
- urls.py
- views.py
- wsgi.py
-db.sqlite3
-manage.py
index.html
{% extends 'ajax/base.html' %}
{% block body %}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Get Your Location</button>
<p id="demo"></p>
<button type="button" id="btn_submit" class="btn btn-primary form-control" disabled>Submit</button>
{% endblock %}
script.js
var pos;
var $demo;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$demo.text("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
pos = position;
var { latitude, longitude } = pos.coords;
$demo.html(`Latitude: ${latitude}<br>Longitude: ${longitude}`);
$('#btn_submit').attr("disabled", null);
}
$(document).ready(function() {
$demo = $("#demo");
$('#btn_submit').on('click', function() {
var data = pos.coords;
data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
$.post("/ajax/", data, function() {
alert("Saved Data!");
});
});
});
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'ajax/css/bootstrap.css' %}"/>
</head>
<body>
{% csrf_token %}
<nav class="navbar navbar-default">
<div class="container-fluid">
</div>
</nav>
<div class="col-md-3"></div>
<div class="col-md-6 well">
<h3 class="text-primary">Python - Django Simple Submit Form With Ajax</h3>
<hr style="border-top:1px dotted #000;"/>
{% block body %}
{% endblock %}
</div>
</body>
<script src = "{% static 'ajax/js/jquery-3.2.1.js' %}"></script>
<script src = "{% static 'ajax/js/script.js' %}"></script>
</html>
models.py
from django.db import models
# Create your models here.
class Member(models.Model):
latitude = models.DecimalField(max_digits=19, decimal_places=16)
longitude = models.DecimalField(max_digits=19, decimal_places=16)
views.py (ajax)
from django.shortcuts import render, redirect
from .models import Member
def index(request):
return render(request, 'ajax/index.html')
def insert(request):
member = Member(latitude=request.POST['latitude'], longitude=request.POST['longitude'])
member.save()
return redirect('/')
urls.py (ajax)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^insert$', views.insert, name="insert")
]
views.py (server)
from django.shortcuts import redirect
def index_redirect(request):
return redirect('/ajax/')
urls.py (server)
from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.index_redirect, name="index_redirect"),
url(r'^ajax/', include("ajax.urls")),
url(r'^admin/', admin.site.urls),
]
It "POST"s the data but it does not appear in the django admin. I trawled many websites searching for answers why but still haven't found any. Thank you again for your help.
I have used jQuery and Ajax to submit the longitude and latitude data to any model you want to store these data in.
in your model.py:
from django.contrib.auth import User
class UserGeoLocation(models.Model):
user = models.OneToOneField(User)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
for your view.py
def save_user_geolocation(request):
if request.method == 'POST':
latitude = request.POST['lat']
longitude = request.POST['long']
UserGeoLocation.create(
user = request.user
latitude= latitude,
longitude = longitude,
)
return HttpResponse('')
now that we have the view we can setup a url endpoint to submit the post request
url('^abc/xyz/$', appname.views.save_user_geolocation)
and Finally for the actual form,
$(document).on('submit', '#id', function(e){
e.preventDefault();
$.ajax(
type='POST',
url = 'abc/xyz',
data : {
lat:position.coords.latitude,
long: position.coords.longitude
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
});
for the last step, lets say you used the js code from the example you linked, then you can assign these coordinates value to variables that will be submitted with the post request that gets triggered when the user clicks on the button, the id here is the id of the form you want to submit the data from, and the e.PreventDefault is to stop the page from reloading when you post the data. Finally, the csrf token is required by django to able to submit the form.
Related
I'm asked to work on a networking website that is like Twitter. I work with HTML,CSS, Javascript for the client-side and Django for the server-side. I'm trying to link between Javascript and Django using JSON and fetch as I want to create a button in each of the users' profile that upon being clicked by the registered user, it makes the registered follow the profile as it is saved in django database as a model containing the follower(follower) and the user followed(following) but upon clicking on follow button (in user.html) it doesn't save any data in the database
in models.py:
class follow(models.Model):
follower = models.ForeignKey("User",on_delete=models.CASCADE, related_name="follower")
following = models.ForeignKey("User",on_delete=models.CASCADE, related_name="following")
in user.html(contains the script):
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded',function(){
document.querySelectorAll('input').forEach(input =>{
input.addEventListener('click', function(){
console.log(input.id);
let follow_username = input.id
fetch('/follow/'+ follow_id, {
method:'PUT',
body: JSON.stringify({
follow: true
})
})
})
}
)
});
</script>
</head>
<body>
<h2>{{x.username}}</h2>
<form>
{% csrf_token %}
<input type="submit" value="follow" name ="follow" id={{x.username}}>
</form>
</body>
</html>
in urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("follow/<str:name>", views.Users, name="follow")
]
in views.py:
def Users(request, name):
x = User.objects.get(username = name)
if request.method == 'PUT':
data = json.loads(request.body)
if data.get('follow') is not None:
user = request.user
anotherr = User.objects.filter(username = name)
another = User.objects.get(username = anotherr).id
follow.objects.create(follower = user, following = another)
return render (request, "network/user.html",{"x":x})
upon clicking on the follow button that present in user.html, no data is created in the database. so what is the problem?
I'll throw my best guesses on what's happening.. Just some improper syntax and undefined variables
View
another / anotherr no, just use x you're already fetching the user at the top of the view
get_or_create will not allow you to have duplicates / follow someone twice (generally a good idea)
Prints are just debugging, remove after you know it's working
def Users(request, name):
x = User.objects.get(username=name)
if request.method == 'PUT':
print('we\'ve hit put')
data = json.loads(request.body)
if data.get('follow') is not None:
print('in follow')
# Note: [User Obj Itself]
# follower = request.user (is: <User Obj>)
# following = x (is: <User Obj>)
followObj, createdBool = follow.objects.get_or_create(follower=request.user, following=x)
print('followObj', followObj)
print('created?', createdBool)
print('past follow')
print('about to render')
return render (request, "network/user.html",{"x":x})
Template
Idk what follow_id is, just use input.id
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded',function(){
document.querySelectorAll('input').forEach(input =>{
input.addEventListener('click', function(){
// this should be true
console.log(input.id == '{{x.username}}');
console.log('Fetch Url:\t' + '/follow/'+ input.id);
fetch('/follow/'+ input.id, {
method:'PUT',
body: JSON.stringify({
follow: true
})
})
})
}
)
});
</script>
</head>
<body>
<h2>{{x.username}}</h2>
<form>
{% csrf_token %}
<input type="submit" value="follow" name ="follow" id={{x.username}}>
</form>
</body>
</html>
If these don't work, tell me what print or console.log got hit or didn't get hit- that'll really help narrow down the issue even more
Edit
Supposedly this, putting a token in a header, will work if you don't want to put a #csrf_exempt decorator (which might be a good idea tbh)
fetch('/follow/'+ input.id, {
method:'PUT',
headers: { 'X-CSRFToken': $('[name=csrfmiddlewaretoken]').val() },
body: JSON.stringify({
follow: true
})
})
I am learning to build dashboard using Django as backend and D3.js for visualization.
Following is my index.html:
{% load static %}
<html>
<script src="https://d3js.org/d3.v7.min.js"></script>
<body>
<h1> Hello! </h1>
<script src={% static "js\linechart.js" %}>
var data = {{ AAPL|safe }};
var chart = LineChart(data, {
x: d => d.date,
y: d => d.close,
yLabel: "↑ Daily close ($)",
width,
height: 500,
color: "steelblue"
})
</script>
</body>
</html>
Data AAPl is extracted from database and the views.py is as follows:
from django.shortcuts import render
from django.http import HttpResponse
from cnxn import mysql_access
import pandas as pd
# Create your views here.
def homepage(request):
sql = ''' select Date, Close from tbl_historical_prices where ticker = 'AAPL' '''
cnxn = mysql_access()
conn = cnxn.connect()
df = pd.read_sql(sql, con=conn)
context = {'AAPL':df.to_json()}
return render(request, 'index.html', context=context)
Function line chart can be viewed here which is being used in js\linechat.js in index.html file.
I can see the Hello! being displayed on the page but can't see the line chart. I am unable to debug the problem. No errors found in console tab either.
How can I display the line plot?
I've added the current page display in attached image.
Close off your script with a src and start a new script tag. The presence of src precludes internal code.
<script src={% static "js\linechart.js" %}></script>
<script>
...
This is my list where i tried to get the value of the of a tag
{% extends 'base.html'%}
{% block body %}
<div onclick="pass()">
{{list1[1]}}
</div>
here i tried to get the value of a tag and have tried to pass info route
<script>
function pass() {
var a = document.getElementsByTagName('a');
var w = console.log(a[0].outerHTML);
window.location = "/info/" + w;
}
</script>
{% endblock %}
but show the following error
Not Found
http://127.0.0.1:5000/info/undefined
this is my info route
#app.route('/info', methods=['GET', 'POST'])
def info():
result = request.get_data
print(result)
return render_template('info.html', result=result)
why it's not displaying any data of within a tag
Thank you in Advance
window.location simply opens an HTML page. window.location = "/info/" + w; creates a route /info/w/ but you've only specified the route /info.
You need to send the a data to the server via a form and use Flask's request object to access it.
I was exploring the mechanism of formsets in Django. Here is a gist of what I did:
Created a sample choicefield form
forms.py
from django import forms
MONTH_CHOICES = (("JANUARY", "January"),
("FEBRUARY", "February"),
("MARCH", "March"),
("DECEMBER", "December"),)
class NameForm(forms.Form):
your_name = forms.ChoiceField(label="Your Name",choices=MONTH_CHOICES)
Added Views Code with a formset instance for the NameForm and data handling.
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect,HttpResponse
from django.forms.formsets import formset_factory
from .forms import NameForm
def index(request):
lfs = formset_factory(NameForm)
if request.method == 'POST':
postedformset = lfs(request.POST)
if postedformset.is_valid():
for formz in postedformset:
print formz.cleaned_data['your_name']
return HttpResponseRedirect('/polls/thanks/')
else:
form = NameForm()
return render(request,'name.html',{'form':lfs})
def thanks(request):
return HttpResponse('Form filled. Thanks!')
3.A HTML for implementing the formset with a bit of javascript for adding and deleting forms
name.html
<html>
<head>
<title>DJANGO - First Forms</title>
</head>
<body>
<form action="/polls/" method="POST">
{{ form.management_form }}
<div class="link-formset">
{{ form }}
</div>
<input type="Submit"/>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.formset/1.2.2/jquery.formset.min.js"></script>
<script>
$('.link-formset').formset({
addText: 'add link',
deleteText: 'remove'
});
</script>
Implementation was done using this using this reference
Question
I was able to add multiple choicefields and save the form without any issues. However, only the choice of the first form was printed when
print formz.cleaned_data['your_name')
was executed. Querydict from request.POST has choices from all forms in formset (refer Update)
Please share your thoughts on this.
PS : I did check on questions like this and this, but still not able to trace the root cause.
Update
For 2 forms in my formset, when I tried to print request.POST, below QueryDict was obtained which has information from both forms..
<QueryDict: {u'form-1-form-TOTAL_FORMS': [u''], u'form-1-form-MIN_NUM_FORMS': [u''], u'form-1-form-MAX_NUM_FORMS': [u''], u'form-1-form-INITIAL_FORMS': [u''], u'form-MAX_NUM_FORMS': [u'1000', u'1000'], u'form-1-your_name': [u'FEBRUARY'], u'form-0-your_name': [u'FEBRUARY'], u'form-MIN_NUM_FORMS': [u'0', u'0'], u'form-INITIAL_FORMS': [u'0', u'0'], u'form-TOTAL_FORMS': [u'2', u'1']}>
I'm working on a Python package that uses Tornado to send data to the browser for visualization. In order to do this, I want the users to be able to write multiple arbitrary modules for the server to render together on a single page -- including each module's own JavaScript.
However, by default, the Tornado's UIModule class's embedded_javascript() method only appends JavaScript to <script>...</script> once per module class. I'm hoping there is a simple way to embed multiple pieces of JS, one for every UIModule (or another way to get the same effect).
Here's a minimal example of what I'm talking about:
import tornado.ioloop
import tornado.web
import tornado.template
class Element(tornado.web.UIModule):
'''
Module to add some custom JavaScript to the page.
'''
def render(self, element):
self.js_code = element.js_code
return ""
def embedded_javascript(self):
return self.js_code
class InterfaceElement(object):
'''
Object to store some custom JavaScript code.
'''
def __init__(self, js_code):
'''
Args:
js_code: Some JavaScript code in string form to add to the page.
'''
self.js_code = js_code
class MainPageHandler(tornado.web.RequestHandler):
def get(self):
elements = self.application.modules
self.render("uitest_template.html", app_name="Testing", elements=elements)
class ThisApp(tornado.web.Application):
def __init__(self, modules):
self.modules = modules
main_handler = (r'/', MainPageHandler)
#settings = {"ui_modules": {"Element": Element}}
settings = {"ui_modules": {"Element": Element},
"template_path": "ui_templates"}
super().__init__([main_handler], **settings)
# Create two objects with some custom JavaScript to render
module_1 = InterfaceElement("var a = 1;")
module_2 = InterfaceElement("var b = 2;")
app = ThisApp([module_1, module_2])
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
And the template for uitest_template.html is just
<!DOCTYPE html>
<head>
<title> Hello World </title>
</head>
<body>
{% for element in elements %}
{%module Element(element) %}
{% end %}
</body>
The rendered page then includes a <script> tag in body that is:
<script type="text/javascript">
//<![CDATA[
var b = 2;
//]]>
</script>
And what I want is:
<script type="text/javascript">
//<![CDATA[
var a = 1;
var b = 2;
//]]>
</script>
Or something like it. Any ideas?
Added - my solution
Based on the answer below, here's how I ended up handling it:
import tornado.ioloop
import tornado.web
import tornado.template
class InterfaceElement(object):
include_js = [] # List of .js files to include
js_code = '' # JavaScript string to include
def __init__(self, include_js=[], js_code=''):
self.include_js = include_js
self.js_code = js_code
class MainPageHandler(tornado.web.RequestHandler):
def get(self):
self.render("modular_template.html",
includes=self.application.include_js,
scripts=self.application.js_code)
class ThisApp(tornado.web.Application):
def __init__(self, modules):
# Extract the relevant info from modules:
self.modules = modules
self.include_js = set()
self.js_code = []
for module in self.modules:
for include_file in module.include_js:
self.include_js.add(include_file)
if module.js_code != '':
self.js_code.append(module.js_code)
main_handler = (r'/', MainPageHandler)
settings = {"template_path": "ui_templates",
"static_path": "ui_templates"}
super().__init__([main_handler], **settings)
module_1 = InterfaceElement(js_code="var a = 1;")
module_2 = InterfaceElement(include_js=["test.js"], js_code="var b = 1;")
app = ThisApp([module_1, module_2])
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()
Which goes with the following template:
<!DOCTYPE html>
<head>
<title> Hello world </title>
</head>
<body>
<!-- Script includes go here -->
{% for file_name in includes %}
<script src="/static/{{ file_name }}" type="text/javascript"></script>
{% end %}
<script type="text/javascript">
// Actual script snippets go here.
{% for script in scripts %}
{% raw script %}
{% end %}
</script>
</body>
embedded_javascript and related methods are (effectively) class-level methods; they must return the same value for any instance of the class. (They're intended to be a kind of dependency-management system, so you can load a piece of javascript only on pages that include a module that needs it)
The only thing that is allowed to vary per instance is the output of render(), so to embed multiple pieces of javascript you should include the script tag in the result of your render() method.