

def test_ajax_fk():
    (app, db, admin) = setup()
    (Model1, Model2) = create_models(db)
    view = CustomModelView(Model2, db.session, url='view', form_ajax_refs={
        'model1': {
            'fields': ('test1', 'test2'),
        },
    })
    admin.add_view(view)
    ok_(('model1' in view._form_ajax_refs))
    model = Model1('first')
    model2 = Model1('foo', 'bar')
    db.session.add_all([model, model2])
    db.session.commit()
    loader = view._form_ajax_refs['model1']
    mdl = loader.get_one(model.id)
    eq_(mdl.test1, model.test1)
    items = loader.get_list('fir')
    eq_(len(items), 1)
    eq_(items[0].id, model.id)
    items = loader.get_list('bar')
    eq_(len(items), 1)
    eq_(items[0].test1, 'foo')
    form = view.create_form()
    eq_(form.model1.__class__.__name__, 'AjaxSelectField')
    with app.test_request_context('/admin/view/'):
        ok_(('value=""' not in form.model1()))
        form.model1.data = model
        ok_((('data-json="[%s, &quot;first&quot;]"' % model.id) in form.model1()))
        ok_(('value="1"' in form.model1()))
    client = app.test_client()
    req = client.get('/admin/view/ajax/lookup/?name=model1&query=foo')
    eq_(req.data.decode('utf-8'), ('[[%s, "foo"]]' % model2.id))
    req = client.post('/admin/view/new/', data={
        'model1': as_unicode(model.id),
    })
    mdl = db.session.query(Model2).first()
    ok_((mdl is not None))
    ok_((mdl.model1 is not None))
    eq_(mdl.model1.id, model.id)
    eq_(mdl.model1.test1, 'first')

dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/tests/sqla/test_basic.py test_ajax_fk/original