geocoding an IP and save using model forms
i have this thing in my models.py file
user = models.ForeignKey('auth.User', unique = True)
latitude = models.DecimalField(max_digits=8, decimal_places=6)
longitude = models.DecimalField(max_digits=8, decimal_places=6)
Availability = models.CharField(max_length=8,choices=STATUS_CHOICES, blank= False, null=False)
Status = models.CharField(max_length=50, blank = True, null= True)
and in forms.py i have
class registerForm(forms.ModelForm):
class Meta:
model=register
fields = ('latitude', 'longitude', 'Availability', 'Status')
now what i want here is to geocode the Ip address of the user and get the latitude and longitude automatically after geocoding the IP and save it to the database. i dont want to allow the user to enter the latitide and longitude manually as it will be an odd one and definately nobody will like to do it manually. i am using GeoIP to geocode the IP address. and in my views.py i have
def Userlocation(request):
if request.method == "POST":
rform = registerForm(data = request.POST)
if rform.is_valid():
register = rform.save(commit=False)
register.user=request.user
register.save()
return render_to_re开发者_运维知识库sponse('home.html')
else:
rform = registerForm()
return render_to_response('status_set.html',{'rform':rform})
i am looking for a way to automatically get the lat,lon from the GeoIP and place it in the latitude longitude field in forms so that the users do not have to manually enter it. and then after entering the status and availability the forms can be saved to database. any help would be greatly appreciated
Overwrite the save method of form to populate latitude & longitude
from django.contrib.gis.utils import GeoIP
class registerForm(forms.ModelForm):
class Meta:
model=register
fields = ('Availability', 'Status')
def save(self, ip_address, *args, **kwargs):
g = GeoIP()
lat, lon = `get the lat & lng`
user_location = super(registerForm, self).save(commit=False)
user_location.latitude = lat
user_location.longitude = lon
user_location.save(*args, **kwargs)
change this line
register = rform.save(commit=False)
to
register = rform.save(ip_address=request.META['REMOTE_ADDR'])
精彩评论