Skip to content Skip to sidebar Skip to footer

Flask-admin Form: Constrain Value Of Field 2 Depending On Value Of Field 1

One feature I have been struggling to implement in flask-admin is when the user edits a form, to constrain the value of Field 2 once Field 1 has been set. Let me give a simplified

Solution 1:

I see two ways of tacking this problem:

1- When Flask-Admin generate the form, add data attributes with the mid of each methodArg on each option tag in the methodArg select. Then have some JS code filter the option tags based on the recipe selected.

EDIT

Here is a tentative try at putting a data-mid attribute on each option:

def monkeypatched_call(self, field, **kwargs):
    kwargs.setdefault('id', field.id)
    if self.multiple:
        kwargs['multiple'] = True
    html = ['<select %s>' % html_params(name=field.name, **kwargs)]
    for (val, label, selected), (_, methodarg) in zip(field.iter_choices(), field._get_object_list()):
        html.append(self.render_option(val, label, selected, **{'data-mid': methodarg.mid}))
    html.append('</select>')
    return HTMLString(''.join(html))

Select.__call__ = monkeypatched_call

The blocker is in the fact that those render calls are triggered from the jinja templates, so you are pretty much stuck updating a widget (Select being the most low-level one in WTForms, and is used as a base for Flask-Admin's Select2Field).

After getting those data-mid on each of your options, you can proceed with just binding an change on your recipe's select and display the methodarg's option that have a matching data-mid. Considering Flask-Admin uses select2, you might have to do some JS tweaking (easiest ugly solution would be to clean up the widget and re-create it for each change event triggered)

Overall, I find this one less robust than the second solution. I kept the monkeypatch to make it clear this should not be used in production imho. (the second solution is slightly less intrusive)

2- Use the supported ajax-completion in Flask-Admin to hack your way into getting the options that you want based on the selected recipe:

First, create a custom AjaxModelLoader that will be responsible for executing the right selection query to the DB:

class MethodArgAjaxModelLoader(sqla.ajax.QueryAjaxModelLoader):
    def get_list(self, term, offset=0, limit=10):
        query = self.session.query(self.model).filter_by(mid=term)
        return query.offset(offset).limit(limit).all()

class RecipeArgAdmin(sqla.ModelView):
    column_list = ('recipe', 'methodarg', 'strvalue')
    form_ajax_refs = {
        'methodarg': MethodArgAjaxModelLoader('methodarg', db.session, MethodArg, fields=['methodarg'])
    }
    column_editable_list = column_list

Then, update Flask-Admin's form.js to get the browser to send you the recipe information instead of the methodArg name that needs to be autocompleted. (or you could send both in query and do some arg parsing in your AjaxLoader since Flask-Admin does no parsing whatsoever on query, expecting it to be a string I suppose [0]. That way, you would keep the auto-completion)

data: function(term, page) {
    return {
        query: $('#recipe').val(),
        offset: (page - 1) * 10,
        limit: 10
    };
},

This snippet is taken from Flask-Admin's form.js [1]

Obviously, this needs some tweaking and parametrising (because doing such a hacky solution would block you from using other ajax-populated select in the rest of your app admin + the update on form.js directly like that would make upgrading Flask-Admin extremely cumbersome)

Overall, I am unsatisfied with both solutions and this showcase that whenever you want to go out of the tracks of a framework / tool, you can end up in complex dead ends. This might be an interesting feature request / project for someone willing to contribute a real solution upstream to Flask-Admin though.


Solution 2:

There is another easy solution that I made and it works

1- Create your first select option normally with data loaded on it and add a hook to it which will add js event listener when it selects change like this.

from wtforms import SelectField

form_extra_fields = {
    'streetname': SelectField(
        'streetname',
        coerce=str,
        choices=([street.streetname for street in StreetsMetadata.query.all()]),
        render_kw={'onchange': "myFunction()"}
        )
    }

**2- Add a JavaScript URL file to the view you want to use this function in, for example.

def render(self, template, **kwargs):
    #using extra js in render method allow use url_for that itself requires an app context

    self.extra_js = [url_for("static", filename="admin/js/users.js")]
    response = render_miror(self, template,**kwargs)
    return response

3- Create a role-protected endpoint that you used for this view that will accept a GET request from JS based on the first value specified for the entry, for example this route returns a list of house numbers by querying the street name that came from the first entry

@super_admin_permission.require(http_exception=403)
@adminapp.route('/get_houses_numbers')
def gethouses():
    request_data = request.args
    if request_data and 'street' in request_data:
        street = StreetsMetadata.query.filter(StreetsMetadata.streetname == request_data['street']).one_or_none()
        street_houses = lambda:giveMeAllHousesList(street.excluded, street.min, street.max)
        if street_houses:
            return jsonify({'code': 200, 'houses': street_houses()})
        else:
            return jsonify({'code': 404, 'houses': []})
    else:
        return jsonify({'code': 400, 'street': []})

now python part completed time for JavaScript

4- We have to define three functions, the first of which will be called when the form build page is loaded and which do two things first, A dummy select entry will be created using JS and append that entry to the same string input container Make string entry read-only to improve user experience Second, it will send a GET request to the specified route to get a list of house numbers using the specified street input value Then get the result and create the option elements and append these options to the dummy selection, you can also select the first option while appending the options.

5- The second function "myFunction" is the hook defined in Python in this part

 render_kw={'onchange': "myFunction()"}

This function will do nothing new, it will only send a GET request when the first specified input value is changed, send a GET request to get a list of new house numbers based on the given street name input value by doing a query on the database, then dump the inner HTML of the dummy selection entry , then create and append new options to it.

6- The last function is the callback function which listens for the change on the dummy select entry created with JS when the user chooses the house number which will be reflected in the main string entry, finally you can click save and you will see it working

Note that this whole idea I created is not as good as the built in flask admin, but if you are looking for the end goal and without any problems you can use it

My JS code

/*
  This Function when run when a form included it will create JS select input with the
  default loaded streetname and add house number on that select this select will used
  to guide creator of the house number or to select the house number
*/
async function onFlaskFormLoad(){

  const streetSelect = document.querySelector("#streetname");
  const checkIfForm = document.querySelector("form.admin-form");
  if (checkIfForm){
    let checkSelect = document.querySelector("#realSelect");
    if (!checkSelect){
      const mySelectBox = document.createElement("select");
      const houseString = document.querySelector("#housenumber");
      const houseStringCont = houseString.parentElement;
      mySelectBox.classList.add("form-control")
      mySelectBox.id = "realSelect";
      houseStringCont.appendChild(mySelectBox);
      mySelectBox.addEventListener("change", customFlaskAdminUnpredefinedSelect);
      houseString.setAttribute("readonly", "readonly");
      const res = await fetch(`/get_houses_numbers?street=${streetSelect.value}`);
      const data = await res.json();
      console.log(data);
      if (data.code == 200 && mySelectBox){
        data.houses.forEach( (houseOption, index)=>{
          if (index == 0){
            houseString.value = houseOption;
          }
          let newHouse = document.createElement("option");
          newHouse.setAttribute("value", houseOption);
          newHouse.innerText = houseOption;
          mySelectBox.appendChild(newHouse);
        });
      }


    }
  }
}

onFlaskFormLoad();


/*
  this function will called to change the string input value to my custom js select
  value and then use that string to house number which required by flask-admin
*/
function customFlaskAdminUnpredefinedSelect(){
  const theSelect = document.querySelector("#realSelect");
  const houseString = document.querySelector("#housenumber");
  houseString.value = theSelect.value;
  return true;
}
/*
   flask admin hook that will listen on street input change and then it will send
   get request to secured endpoint with role superadmin required and get the housenumbers
   using the streetname selected and then create options and add to my select input
*/
async function myFunction(){
  const streetSelect = document.querySelector("#streetname");
  const houseString = document.querySelector("#housenumber");
  const houseStringCont = houseString.parentElement;

  const theSelect = document.querySelector("#realSelect");
  const res = await fetch(`/get_houses_numbers?street=${streetSelect.value}`);
  const data = await res.json();
  console.log(data);
  if (data.code == 200 && theSelect){
    theSelect.innerHTML = "";
    data.houses.forEach( (houseOption, index)=>{
      if (index == 0){
        houseString.value = houseOption;
      }
      let newHouse = document.createElement("option");
      newHouse.setAttribute("value", houseOption);
      newHouse.innerText = houseOption;
      theSelect.appendChild(newHouse);
    });
  }
}

Now if I change the street name of the first specified input I will get a new list containing the numbers based on the first input value, note if you have a way to create a python field that accepts the non-predefined options then there is no need to create dummy input you can create and append the new options Directly to second select input

final result

enter image description here


Post a Comment for "Flask-admin Form: Constrain Value Of Field 2 Depending On Value Of Field 1"