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