trying to auto populate fields using django views
my question is similar to this question em using geoip to find the latitide and longitude of a user through IP address. i am doing something like this in my views
g=Geoip()
lat,lon=g.lat_lon(some ip)
here i want the forms fields 开发者_如何学Pythonto be filled in automatically something like
latitude=lat
longitude=lon
userform.save()
and dont want to overwrite the save method as i am fairly new to django and no idea about how they work. i tried the above link code but unable to make it work for me. how can i autopopulate the latitude and longitude fields in views.py
Ah, just dive right in. Unless you do something really stupid you're not going to hurt anything. BTW, "stupid" includes doing this on your production site with an un-backed up database.
An important point to remember is that you're not overwriting the save()
method, you're supplying a class-specific version of it which can, in turn, call the parent's save()
method. E.g.
class MyModel(models.Model):
...
def save(self):
# whatever you need to do to the object before the save
super(MyModel, self).save() # replace MyModel with *your* class name
Alternatively, you can call super()
first and then do stuff afterward. If all your routine did was call super()
you would have a correct (but useless) save()
method.
See the Python docs for more insight/info.
精彩评论