Well, I recently approached to flask-admin and I cannot figure out how to solve this issue. I know that I can use form_choices
to restrict the possible values for a text-field by specifying a list of tuples. Anyway, form_choices
allows to select only one value at a time. How can I specify that in some cases I may need of a comma-separated list of values?
I tried this workaround:
form_args = {
'FIELD': {
'render_kw': {"multiple": "multiple"},
}
}
but, even though a multiselect input actually appears on the webpage, only the first value is saved.
EIDT 05/13/2017
By playing a bit with flask-admin I found two possible (partial-)solution for my question, both of them with specific drawbacks.
1) The first deals with the use of Select2TagsField
from flask_admin.form.fields import Select2TagsField
...
form_extra_fields = {
'muri': Select2TagsField()
}
With this method is it possible to easily implement select menu for normal input text, even though at present I do not understand how to pass choices to Select2TagsField. It works well as a sort of multiple free text input. However, as far as I understand, it is not possible to pair Select2TagsField and form_choices
2) The second is a bit longer but it offers some more control on code (at least I presume).
Still it implies the use of form_choices
, but this time paired with on_model_change
form_args = {
'FIELD': {
'render_kw': {"multiple": "multiple"},
}
}
form_choices = {'FIELD': [
('1', 'M1'), ('2', 'M2'), ('3', 'M3'), ('4', 'M4')
]}
...
def on_model_change(self, form, model, is_created):
if len(form.FIELD.raw_data) > 1:
model.FIELD = ','.join(form.FIELD.raw_data)
This solution, despite the former one, allows to map choices and works well when adding data to the model, but in editing it gives some problems. Any time I open the edit dialog the FIELD is empty. If I look at the data sent to the form (with on_form_prefill
by printing form.FIELD.data
) I get a comma separated string in the terminal but nothing appear in the pertinent select field on the webpage.