Reputation: 791
I'm new to geodjango
i want to make real-world gis
project with geodjango
to find locations
I tried this
class Place(models.Model):
user= models.ForeignKey(Account,on_delete=models.CASCADE)
address = models.CharField(max_length=100)
slug = models.SlugField(unique=True,blank=True,null=True)
description = models.TextField()
location = models.PointField(srid=4326)
views.py
class PalceCreateView(CreateView):
queryset = Place.objects.all()
def form_valid(self,form):
lat = self.request.POST['lat']
lon = self.request.POST['long']
coords = Point(lat,lon)
form.instance.location = coords
form.save()
return super(PalceCreateView,self).form_valid(form)
my forms.py
class PlaceForm(forms.ModelForm):
class Meta:
model = Place
fields = [
'name','description','location','city','tags'
]
read_only_fields = ['location']
my template
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
<input type="hidden" name="lat" id="lat">
<input type="hidden" name="long" id="long">
{{form}}
<input type='submit' value='submit'>
</form>
<script>
navigator.geolocation.getCurrentPosition(function(location) {
lat = location.coords.latitude;
long = location.coords.longitude;
document.getElementById('lat').innerHTML= lat
document.getElementById('long').innerHTML = long
});
</script>
but when I submit the form it will raise this error
Invalid parameters given for Point initialization.
How can I assign it to a location field?
Upvotes: 3
Views: 1151
Reputation: 23134
You want to prevent the user from modifying the initial point and you want to add a second field for a potential point input.
You can achieve this by adding an extra form.PointField
directly into the form definition:
from django.contrib.gis import forms
class PlaceForm(forms.ModelForm):
new_location = forms.PointField()
class Meta:
model = Place
fields = [
'name','description','location','city','tags', 'new_location'
]
read_only_fields = ['location']
then in your view:
class PalceCreateView(CreateView):
queryset = Place.objects.all()
def form_valid(self,form):
new_location = self.request.POST['new_location']
form.instance.location = new_location
form.save()
return super(PalceCreateView,self).form_valid(form)
Or you can modify your existing solution (lat, long
as a couple of form.FloatField
]2s) as follows:
class PlaceForm(forms.ModelForm):
lat = forms.FloatField()
long = forms.FloatField()
class Meta:
model = Place
fields = [
'name','description','location','city','tags', 'lat', 'long'
]
read_only_fields = ['location']
and your view remains the same.
Upvotes: 1
Reputation: 791
fixed just by using changing the coordinated to float type
def form_valid(self,form):
lat = float(self.request.POST.get('lon'))
lon = float(self.request.POST.get('lat'))
Upvotes: 2