我正在尝试使用GeoIP将lat,lon直接插入到表单中。有一些问题,很可能是因为我在本地主机的开发模式下,无法正确解析IP地址。
我正在尝试创建一个虚拟IP地址,以查看lat,lon是否实际被确定并在表单中设置('google.com')。不幸的是,这会导致表单中未正确保存的其他元素出现问题,特别是作者属性。
产生的错误:
'NoneType' object has no attribute 'author'
这是观点:
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext
from django.core.urlresolvers import reverse
from myapp.report.models import Story, UserProfile
from myapp.report.forms import ProfileForm, StoryForm
from django.contrib.auth.decorators import login_required
from django.contrib.gis.utils import GeoIP
from django.conf import settings
@login_required
def submit_story(request):
remote_address = request.META['REMOTE_ADDR']
if settings.DEBUG:
remote_address = 'google.com'
if request.method =="POST":
story_form = StoryForm(request.POST, request.FILES)
if story_form.is_valid():
new_story = story_form.save(ip_address=remote_address)
new_story.author = request.user
new_story.save()
return HttpResponseRedirect("/report/all/")
else: # GET request
story_form = StoryForm()
return render_to_response("report/report.html", {'form': story_form}, context_instance=RequestContext(request))
这是模型:
class Story(models.Model):
objects = StoryManager()
title = models.CharField(max_length=100)
topic = models.CharField(max_length=50)
copy = models.TextField()
author = models.ForeignKey(User, related_name="stories")
zip_code = models.CharField(max_length=10)
latitude = models.FloatField(blank=False, null=False)
longitude = models.FloatField(blank=False, null=False)
date = models.DateTimeField(auto_now=True, auto_now_add=True)
pic = models.ImageField(upload_to='pictures', blank=True)
caption = models.CharField(max_length=100, blank=True)
def __unicode__(self):
return " %s" % (self.title)
这是表格:
from django import forms
from myapp.report.models import UserProfile, Story
from django.contrib.gis.utils import GeoIP
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
class StoryForm(forms.ModelForm):
class Meta:
model = Story
exclude = ('author','latitude', 'longitude')
def save(self, ip_address, *args, **kwargs):
g = GeoIP()
lat, lon = g.lat_lon(ip_address)
user_location = super(StoryForm, self).save(commit=False)
user_location.latitude = lat
user_location.longitude = lon
user_location.save(*args, **kwargs)