如何从ModelView类flask_admin添加数据库上的数据?

时间:2015-07-07 08:20:18

标签: python flask flask-admin

我在我的管理网站中使用Flask_Admin进行申请。我输入地址。之后,这个地址向Google Maps做请求并获取坐标:lat,lng。我应该在数据库上保存这个坐标? 这是我在Flask_Admin视图上的代码

class EventAdmin(sqla.ModelView):
column_display_pk = True
la = ''
lo = ''
form_columns = ['title', 'description', 'date', 'cover', 'city', 'category', 'address']
form_extra_fields = {
    'cover': form.ImageUploadField('Cover',
                                   namegen=prefix_name,
                                   base_path=get_path('events'),
                                   thumbnail_size=(250, 250, True),
                                   allowed_extensions=app.config['ALLOWED_EXTENSIONS'])
}

column_exclude_list = ('longi', 'lati')
def on_model_change(self, form, model, is_created):
    address = unicode(model)
    url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address.encode('utf-8')
    response = urllib2.urlopen(url)
    jsongeocode = response.read().encode('utf-8')
    data = eval(jsongeocode)
    coordinates = data['results'][0]['geometry']['location']
    self.la = coordinates['lat']
    self.lo = coordinates['lng']

1 个答案:

答案 0 :(得分:1)

' LA'并且' lo'属性未绑定到Model类,因此它们不会持久保存到数据库中。相反,您应该将从谷歌api获得的响应(经度和纬度)绑定到您的模型类属性(您已命名为' longi'和#39; lati'。所以基本上你隐藏来自用户的

column_exclude_list = ('longi', 'lati')

因为您不希望用户输入该数据(您正在为他执行此操作)。 当用户提交表单时,on_model_change方法获取用户提交的模型实例(标题,描述,日期等的值)。现在它只需添加longi和lati值 相反,你应该有这个

def on_model_change(self, form, model, is_created):
    address = unicode(model)
    url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address.encode('utf-8')
    response = urllib2.urlopen(url)
    jsongeocode = response.read().encode('utf-8')
    data = eval(jsongeocode)
    coordinates = data['results'][0]['geometry']['location']
    model.lati = coordinates['lat']
    model.longi = coordinates['lng']