geocoding an IP and save using model forms

♀尐吖头ヾ 提交于 2019-12-01 11:21:38

问题


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_response('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


回答1:


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)



回答2:


change this line

register = rform.save(commit=False)

to

register = rform.save(ip_address=request.META['REMOTE_ADDR'])


来源:https://stackoverflow.com/questions/4281754/geocoding-an-ip-and-save-using-model-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!