我很麻烦,有人可以帮我吗?我一直在使用这个例子http://www.rkblog.rk.edu.pl/w/p/shops-near-you-geographic-features-geodjango/,但是在Django 2.0中我并没有获得成功,不会显示任何错误但不起作用,我的代码是:< / p>
PS:我的github是https://github.com/rafaelribeiroo/magalu-finder
Models.py
from django.db import models
from django.contrib.gis.db import models as gis_models
from django.contrib.gis import geos
from urllib.error import URLError
from geopy.geocoders import GoogleV3
class Produto(models.Model):
# codigo = models.IntegerField()
# Não tem sentido o atributo acima, uma vez que o
# Django gera um ID automático
name = models.CharField('Nome', max_length=50, blank=False)
value = models.DecimalField(
'Valor',
max_digits=7,
decimal_places=2,
blank=False)
description = models.TextField(
'Descrição',
max_length=999,
blank=False)
class Meta:
ordering = ['id']
verbose_name = 'Produto'
verbose_name_plural = 'Produtos'
def __str__(self):
return self.name
class Loja(models.Model):
product = models.ManyToManyField(Produto, verbose_name='produtos')
filial = models.IntegerField('Código Filial', blank=False)
cep = models.IntegerField('CEP', blank=False)
address = models.CharField(max_length=100)
city = models.CharField(max_length=50)
# Qual a diferença entre Blank e Null?
# O argumento BLANK servirá apenas para validar os inputs
# Já o NULL, para o banco de dados
location = gis_models.PointField(
'Longitude/Latitude',
geography=True,
blank=True,
null=True
)
description = models.TextField(
'Descrição simples',
max_length=500,
blank=False)
gis = gis_models.Manager()
objects = models.Manager()
class Meta:
ordering = ['filial']
verbose_name = 'Loja'
verbose_name_plural = 'Lojas'
def __str__(self):
return str(self.filial)
def save(self, *args, **kwargs):
if not self.localizacao:
address = ('{0} {1}'.format(self.city, self.address))
address = address.encode('utf-8')
geocoder = GoogleV3(
api_key='AIzaSyAzxFH7ttJU0SAqlW0m7O4EYL9OZNYD85U'
)
try:
_, latlon = geocoder.geocode(address, timeout=10)
except (URLError, ValueError):
pass
else:
point = ('POINT({} {})'.format(latlon[1], latlon[0]))
self.location = geos.fromstr(point)
super(Loja, self).save(*args, **kwargs)
Views.py:
from django.shortcuts import render
from django import forms
from urllib.error import URLError
from django.contrib.gis import geos
from django.contrib.gis.measure import D
from django.template import RequestContext
from geopy.geocoders import GoogleV3
from .models import Loja
from .forms import LojaForm
def geocode_address(address): # Converter Lat/Lon em Endereço
address = address.encode('utf-8')
geocoder = GoogleV3(
api_key='AIzaSyAzxFH7ttJU0SAqlW0m7O4EYL9OZNYD85U'
)
try:
_, latlon = geocoder.geocode(address)
except (URLError, ValueError):
return None
else:
return latlon
def get_lojas(longitude, latitude): # Obter a localização atual do cliente
current_point = geos.fromstr('POINT {} {}'.format(longitude, latitude))
distance_from_point = {'km': 10} # Mostrar as lojas há 10km's
loja = Loja.objects.filter(
location__distance_lte=(
current_point,
D(**distance_from_point)
)
)
loja = loja.distance(current_point).order_by('distance')
return loja.distance(current_point)
def geolocation(request):
if request.method == 'POST':
form = LojaForm(request.POST)
form = forms.AddressForm(request.POST)
if form.is_valid():
address = form.cleaned_data['address']
location = geocode_address(address)
if location:
latitude, longitude = location
loja = get_lojas(longitude, latitude)
else:
form = LojaForm
return render(
'location.html',
{'form': form, 'loja': loja},
context_instance=RequestContext(request)
)
表单:
from django import forms
from .models import Loja
class LojaForm(forms.ModelForm):
class Meta:
model = Loja
fields = [
'filial',
'cep',
'address',
'city',
'location',
'description',
]
最后,我的 location.html
<form method="post" action="./">
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Search" />
</form>
{% if loja %}
<h2>Lojas próximas a você</h2>
<ul>
{% for cont in loja %}
<li><b>{{ loja.filial }}</b>: Distância: {{ loja.distance }}</li>
{% endfor %}
</ul>
<div class="map" style="width: 400px; height: 400px;"></div>
{% endif %}