我最近有這個要求,並有一點點被帶走,但我想我會分享。 (Django 2.0。)
我創建了一個30個字符的CharField來包含座標,如輸入N 35º 44.265 W 41º 085.155
(我不知道在哪裏,順便說一下......)並安排模型來存儲字段值。
import re
from django.core.exceptions import ValidationError
COORDINATES_REGEX = r'(?:[NS])\s*([0-9]{2})[\º\°]?\s+([0-9]{1,3}\.[0-9]{3})\s*(?:[EW])\s*([0-9]{2,3})[\º\°]?\s+([0-9]{2,3}\.[0-9]{3})'
def decode_coords_string(str):
"""
Given a string, converts it to a decimal (lat, lng, 'OK', matched_string) tuple.
If invalid, returns "(None, None, <some reason>, None)."
Test for errors by checking that the coordinate is not 'None.'
'matched_string' returns the actual extent of the matched string regardless of where in the input-string it was,
for sanitizing the input when storing it in the database. (If the input string contains only blanks, we should
store an empty-string.)
The model will replace the field-value with this matched-string.
"""
# Dispose of empty input, returning an empty string(!) as the 'matched_string' in this case.
r = re.compile(r'^\s*$')
if r.match(str):
return (None, None, 'Empty string', '')
# Build the regex for coordinates.
r = re.compile(COORDINATES_REGEX, re.IGNORECASE)
# Try to match the string
p = r.match(str)
if p is None:
return (None, None, 'Syntax error', None)
# Get the pieces and expressly convert them to numeric types
(lat_degs, lat_mins, lng_degs, lng_mins) = p.groups()
lat_degs = int(lat_degs)
lat_mins = float(lat_mins)
lng_degs = int(lng_degs)
lng_mins = float(lng_mins)
# Throw out anything that simply does not make sense
if (lat_degs > 180) or (lng_degs > 180) or (lat_mins > 60.0) or (lng_mins > 60.0):
return (None, None, 'Degs/Mins value(s) out of bounds')
latitude = float(lat_degs) + (lat_mins/60.0)
longitude = (float(lng_degs) + (lng_mins/60.0)) * -1.0
return (latitude, longitude, 'OK', p.group())
def validate_coords(str):
"""
Simple validator for a coordinate string.
"""
(lat, lng, reason, str2) = decode_coords_string(str)
if lat is None:
raise ValidationError('Invalid coordinates: ' + reason)
輸入CharField指定validators=[validate_coords]
還要注意的是度符號可以指定多種方式或完全省去。
和模型包括以下短方法:
def save(self, *args, **kwargs):
"""
Calculate and automatically populate the numeric lat/long figures.
This routine assumes that the string is either empty or that it has been validated.
An empty string – or, for that matter, an invalid one – will be (None, None).
"""
(lat, lng, reason, cleaned) = decode_coords_string(self.coordinate_str)
self.coordinate_str = cleaned
self.latitude = lat
self.longitude = lng
super().save(*args, **kwargs)
在admin.py
我排除latitude
和longitude
字段(這兩者都是浮動場)從視圖,爲了避免混淆用戶。數字字段會自動計算,但不會顯示。
這是一個簡單而且非常容易實現的解決方案,儘管不是太優雅。沒有想到它 - 謝謝! –