我最近有这个要求,有点得意忘形,但我想我会分享。 (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
andlongitude
字段(两者都是 Float 字段),以避免混淆用户。数字字段会自动计算,但不会显示。