The second part of the tutorial to map coordinates on an app with Django


Part I: www.jeffreyteruel.com/article/3

Complete Project: https://github.com/jteruel/checkin-map-django-googlemaps


During the first part of the tutorial, we created the front end map and form to enter our data, but we haven’t developed the workings of our app. We'll finish the application on this part.

Creating the App Functions

Our process of work will be the following: create an app, a database model , create our functions and record API. Then, we will make changes to the urls.py files on both the record and main app. To begin, in our record app's folder, we need to define what the database will read and make a model. To create our model, enter the following code in your record models.py file:  

from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.contrib import admin from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.db import models from django.contrib.auth.models import User from django.utils.deconstruct import deconstructible from django.utils import timezone import datetime class Record(models.Model):     location = models.CharField(max_length=100)     text = models.CharField(max_length=500)     created = models.DateTimeField(auto_now_add=True)     updated = models.DateTimeField(auto_now=True)     latitude = models.DecimalField(max_digits=9, decimal_places=6, default=None)     longitude = models.DecimalField(max_digits=9, decimal_places=6, default=None)


With this, our database record for each location input will include our location name, our comments, the date it was created, and the latitude and longitude. Note that for the coordinates we set the default decimal places to 6 to allow for better accuracy. After checking it all, run python manage.py makemigrations record, followed by python manage.py migrate to update your database to create a new record column to store your check-ins. 

Now we’ve completed what we needed for the database, on our views.py file we will import the necessary requirements and Record model. We add in geolocator = Nominatim() before any function to get Geopy to work. Our create_record function will take the data from our entry form, geocode the address, and return the latitude and longitude for database entry. We’ll also create our view for the homepage and the function to enter a new location entry. It should now look something similar to this:  

from django.http import HttpResponse, HttpResponseRedirect from django.core.exceptions import ObjectDoesNotExist from django.shortcuts import render, get_object_or_404 from django.utils.crypto import get_random_string from django.contrib.auth.models import User from .models import Record from .forms import RecordForm from django.contrib.contenttypes.models import ContentType from geopy.geocoders import Nominatim #add for DRF API to work from rest_framework import generics from .serializers import RecordSerializer geolocator = Nominatim() #View to see all points def record_map(request):           return render(request, "home.html") #create a new location def create_record(request):     form = RecordForm(request.POST or None)     if form.is_valid():         instance = form.save(commit=False)         #get coordinates         location = geolocator.geocode(instance.location)         instance.latitude = location.latitude         instance.longitude = location.longitude         instance.save()         return HttpResponseRedirect('/')     context = {           "form":form     }     return render(request, "record/create.html", context)


The last task we have to do is to create our records rest API. Following the Django Rest Framework’s instructions, we first create a serializers.py file within our app with the following code:  

#record/serializers.py 

from rest_framework import serializers

from .models import Record class RecordSerializer(serializers.ModelSerializer):

    class Meta:

       model = Record

       fields = (["id","location","text","created","latitude","longitude"])


Then we’ll add the following lines to record/views.py file just before geolocator = Nominatim() and at the end:  


#add for DRF API just before geolocator = Nominatim()

from rest_framework import generics

from .serializers import RecordSerializer

#API to get all records

class RecordAPIView(generics.ListAPIView):  

   """This class defines the create behavior of our rest api."""

   queryset = Record.objects.all()

   serializer_class = RecordSerializer

 


For our form to work, we’ll add the following lines to our record/forms.py file:


from django import forms

from .models import Record

class RecordForm(forms.ModelForm):

   location = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}), required =True)

   text = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}), required = True)

   class Meta:

       model = Record

       fields = [ 

         "location","text",

       ]


Finally, we’ll go our empty record/urls.py file and write in:

from django.conf.urls import url

from .views import(

create_record,

RecordAPIView,

record_map,

   )

urlpatterns = [

    url(r'^create/$', create_record, name="create_record"),

   url(r'^api/$', RecordAPIView.as_view(), name="record API"),

   url(r'^view/$', record_map, name="record map"),

]


For our app to recognize our record app urls, we go back to our main app urls.py and add url(r'^record/', include('record.urls')), to our url patterns. Your application should work now.

Should you decide to migrate the app to another server, make sure you have a requirements.txt file made within your project folder. To do so, enter the command pip freeze > requirements.txt.

This should at least get you started on Django and coding apps dealing with displaying coordinates with Google Maps. There are better ways to accomplish this task, but tutorial hopefully this gave you an idea on the workflow and methods you can apply when doing so. 


Contact Form