I'm trying to insert the lat, lon directly into a form using GeoIP. There have been issues, more than likely because I'm in development mode with local host and the IP address can't be properly resolved.
I'm trying to create a dummy IP address just to see if the lat, lon are actually being determined and set in the form ('google.com'). Unfortunately, this is causing problems with other elements in the form not being properly saved, specifically the author attribute.
The resulting error:
'NoneType' object has no attribute 'author'
This is the view:
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))
This is the model:
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)
This is the form:
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)