Search code examples
pythonflaskflask-admin

How add data on database from ModelView class flask_admin?


I use Flask_Admin in my site of admin for application. And I type address. After that, this address doing request to Google Maps and take coordinates: lat, lng. I should save this coordinates on database? This is my code on Flask_Admin view

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']

Solution

  • 'la' and 'lo' properties are not bound to the Model class so they will not be persisted to the database. Instead, you should bind the response (longitude and latitude) you get from the google api to your Model class properties (which you have named 'longi' and 'lati'. So basically you hide them from the user with

    column_exclude_list = ('longi', 'lati')
    

    Because you don't want the user to enter that data (you are doing that for him). When the user submits the form, your on_model_change method gets the model instance the user submited (with the values for title, description, date ...) . Now it only has to add the longi and lati values.
    Instead you should have this

    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']