对 IP 进行地理编码并使用模型形式保存 [英] geocoding an IP and save using model forms
问题描述
我的models.py文件中有这个东西
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)
在forms.py中我有
and in forms.py i have
class registerForm(forms.ModelForm):
class Meta:
model=register
fields = ('latitude', 'longitude', 'Availability', 'Status')
现在我想要的是对用户的IP地址进行地理编码,并在对IP进行地理编码后自动获取纬度和经度并将其保存到数据库中.我不想让用户手动输入纬度和经度,因为这会很奇怪,而且肯定没有人愿意手动输入.我正在使用 GeoIP 对 IP 地址进行地理编码.在我的 views.py 中,我有
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_response('home.html')
else:
rform = registerForm()
return render_to_response('status_set.html',{'rform':rform})
我正在寻找一种方法来自动从 GeoIP 获取纬度,经度并将其放置在表单中的纬度经度字段中,以便用户不必手动输入它.然后在输入状态和可用性后,表格可以保存到数据库中.任何帮助将不胜感激
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
推荐答案
覆盖表单的save方法来填充纬度&经度
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)
这篇关于对 IP 进行地理编码并使用模型形式保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!