我遵循了一个优秀的指南(https://matthewdaly.co.uk/blog/2016/03/26/building-a-location-aware-web-app-with-geodjango/)并在Django 1.9 / Python 3中开发了一个可以正常工作的应用程序。
现在我正在尝试将上述应用程序集成到Django 1.8 / Python 2.7中的真正django项目中。我再次按照上面的指南修改Django 1.8 / python 2.7的代码。 我提交数据时遇到问题。无法调用form_valid。 我的models.py:
from django.contrib.gis.db import models
class Venue(models.Model):
name = models.CharField(max_length=200)
location = models.PointField()
def __str__(self):
return self.name
class Event(models.Model):
name = models.CharField(max_length=200)
datetime = models.DateTimeField()
venue = models.ForeignKey(Venue)
def __str__(self):
return "%s - %s" % (self.name, self.venue.name)
我的views.py:
class LookupView(FormView):
template_name = 'gigs/lookupresults.html'
form_class = LookupForm
success_url = '/'
def get(self, request):
return render_to_response('gigs/lookup.html', RequestContext(request))
def form_valid(self, form):
# Get data
latitude = form.cleaned_data['latitude']
longitude = form.cleaned_data['longitude']
# Get today's date
now = timezone.now()
# Get next week's date
next_week = now + timezone.timedelta(weeks=1)
# Get Point
location = Point(longitude, latitude, srid=4326)
# Look up events
events = Event.objects.filter(datetime__gte=timezone.now()).filter(datetime__lte=next_week)
# Render the template
return render_to_response('gigs/lookupresults.html', {
'events': events
})
my urls.py:
urlpatterns = patterns(
'my_project.gigs.views',
url(r'^$', LookupView.as_view(), name='lookup'),
)
my forms.py:
from django.forms import Form, FloatField
class LookupForm(Form):
latitude = FloatField()
longitute = FloatField()
我的第一个模板lookup.html
{% extends "gigs/gigs_base.html" %}
{% block content %}
<form role="form" action="/gigs/" method="post">{% csrf_token %}
<div class="form-group">
<label for="latitude">Latitude:</label>
<input id="id_latitude" name="latitude" type="text" class="form-control"></input>
</div>
<div class="form-group">
<label for="longitude">Longitude:</label>
<input id="id_longitude" name="longitude" type="text" class="form-control"></input>
</div>
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
<script language="javascript" type="text/javascript">
navigator.geolocation.getCurrentPosition(function (position) {
var lat = document.getElementById('id_latitude');
var lon = document.getElementById('id_longitude');
lat.value = position.coords.latitude;
lon.value = position.coords.longitude;
});
</script>
{% endblock %}
提交后我的模板:
{% extends "gigs/gigs_base.html" %}
{% block content %}
<ul>
{% for event in events %}
<li>{{ event.name }} - {{ event.venue.name }}</li>
{% endfor %}
</ul>
{% endblock %}
当我运行localhost:8000 / gigs时,模板呈现正常,但是当我提交数据时,它什么也没显示。 当我执行命令时:
Event.objects.filter(datetime__gte=timezone.now()).filter(datetime__lte=next_week)
在django shell中运行正常。 我无法弄清楚为什么我按照上面的指南开发的第一个简单的应用程序工作正常,而新的集成应用程序没有。 有什么建议吗?
答案 0 :(得分:0)
在模板lookup.html中,您已设置:
<form role="form" action="/gigs/" method="post">
尝试将其更改为:
<form role="form" method="post">