4

One of my models has latitude and longitude fields which are stored in the database as floating point numbers. I like to keep it this way, because it allows me to work with them most efficiently.

I'd like the users to be able to edit them in the stock admin interface in this format: (+/-)DD MM SS.S (that's how most GPS devices present coordinates to the end user).

I've thought of three ways of implementing this:

  1. Use GeoDjango - too much overhead, I simply don't need the full framework only for two fields.
  2. Define a custom model field, somehow in this way. Seems like a lot of coding and I'm not entirely sure whether I would be able to access the floating point representation easily using the Django database interface.
  3. Use MultiValueField and MultiWidget - this wouldn't be an entirely bad solution, but is quite poorly documented and also involves a bit of coding and unnecessary widgets for degrees, minutes and seconds.

But ideally, I'd like to do this:

  • Use a custom form field which would use the standard TextInput form widget and standard FloatField model field.

I'm sure that the to_python() method could handle text input and convert it to float. But how do I tell Django to convert float to my lat/lng representation when editing the model? And how do I stick it all together?

4

2 に答える 2

3

モデルにフィールドを追加して座標データを保持し、モデルのsave()メソッドでこれらを緯度と経度の数値に変換してみませんか? 次に、管理画面で緯度/経度を読み取り専用にして、値を表示できるようにしますが、編集はできません。または、それらをまったく表示しないことにすることもできます。

例えば:

class Location(models.Model):

    latitude = ...
    longitude = ...

    lat_degrees = models.IntegerField()
    lat_minutes = models.IntegerField()
    lat_seconds = models.FloatField()

    def save(self, *args, **kwargs):
        # Do the maths here to calculate lat/lon
        self.latitude = ... 
        self.longitude = ...
        super(Location, self).save(*args, **kwargs)

フィールドも必要になると思いますがlon_degrees、私は座標の専門家ではありません。私はそれらを例から除外しました。管理者用の新しいウィジェットを作成してうまく表示したり、オーバーライドchange_form.htmlして3つのフィールドを同じ行に表示したりすることもできますが、それはこの回答の範囲をわずかに超えています.

于 2011-08-28T10:40:59.967 に答える