I just started a web app using Django and HTML/Javascript templates.
My Django spot
app contains a Spot
model that is sent to a HTML template - to be used with the Google Map Api. I've encountered a problem when looping over the variable spots
containing Spot.objects.all()
.
It seems the problem comes from the way I send the data to the HMTL file.
----------------------------------------- Spot
Django-app : models.py --------------------------------------------
class Spot(models.Model):
idn = models.IntegerField(unique = True)
name = models.CharField(max_length = 200)
longitude = models.FloatField()
latitude = models.FloatField()
------------------------------------------------- HTML / JS -----------------------------------------------
<script type="text/javascript">
var IDs = []
var names = []
var lat = []
var lng = []
{ % for spot in spots % }
IDS.push( {{spot.idn}} );
names.push( {{spot.name}} );
lat.push( {{spot.latitude}} );
lng.push( {{spot.longitude}} );
{ % endfor % }
Then, the lists do not contain any data that can be used afterwards. Worse, the HTML file does not work if the names.push( {{spot.name}} )
is un-commented.
----------------------------------------- Spot
Django-app : views.py --------------------------------------------
from spots.models import Spot
def index(request):
return render(request, 'index.html', {'spots':Spot.objects.all()})
Thanks to the other stackoverflow questions (listed below), I also tried to serialize the Spot.objects.all()
either with django.core.serializers.serialize("json", Spot.objects.all() )
or by creating my own serializer (thanks to Django_REST). The problem remains the same. So is the problem in the way I parse my data with JS?
I've look the following link :
- Returning JSON array from a Django view to a template
- django for loop in a .html template page (newbie)
- Django FOR LOOP in JavaScript
with no success. So if the answer is included or related to these topics, would you mind explaining me something I've been working around for days ...
EDIT: The problem was plural:
- Serializing the data (or not ; I did not for now but everyone who answered agreed to say that it's better to)
- Adding the quotes from
{{ spot.name }}
to'{{ spot.name }}'
, only to non Integer/Float models (i.e. only themodels.CharFields
fields) - Google Maps Api may return errors for some (longitude, latitude) tuples even if they are well-defined