Search code examples
pythonvariablesflaskcategoriesflash-message

Assigning flash categories to iterated variables


I'm trying assign flash categories to an iterable variable that will generate within a form.

My HTML:

   <select name="values" size="10" multiple>
       {% with cols = get_flashed_messages
                       (category_filter="columns"),
                       vals = get_flashed_messages
                       (category_filter="{{val_by_col}}")%}
                   {% for col in cols %}
                       <optgroup label = {{ col }}>
                           {% for val in vals %}
                               <option>
                                   {{ val }}
                               </option>
                           {% endfor %}
                       </optgroup>
                   {% endfor %}
       {% endwith %}
       <input type=submit value=submit>
   </select>
</form>
**Yields HTML Select Form:**
 COLUMN 1
   ALL FLASH VALUES
 COLUMN 2
   ALL FLASH VALUES

However, what I'm trying to accomplish is:

**IDEAL HTML Select Form:**
 COLUMN 1
   COLUMN 1 FLASH VALUES
 COLUMN 2
   COLUMN 2 FLASH VALUES

I'm trying to achieve this through an incremental, iterable variable in my Python:

val_by_col = 0
  for col in col_list:
  val_by_col = int(val_by_col ) + 1
  flash(col, 'columns')
    for val in col:
      flash(val, category=val_by_col )

This way, I was hoping by incrementing val_by_col I could use flashes like you would iterate key, value pairs in dictionaries. Using combinations of str(), f'""' and ""{{}}"" has not yielded proper results.

Perhaps I can append the values to a nested dictionary and iterate through those as flashes to generate the form?? Thanks!!


Solution

  • I could not figure out how to populate the select form with my original vision, so I came up with a compromise.

    Rather than try to separate columns / values in the select form:

    <optgroup label=<column 1>>  
    <options> all column 1 values
    </options></optgroup> 
    <optgroup label=<column 2>>  
    <options> all column 2 values 
    </options></optgroup>
    

    I instead, within my for loop, include the column and flashed that along side with the value:

    for col in enu_cols:
        flash(df.columns[int(col)], "message")
        for val in range(len(df[df.columns[int(col)]].unique())):
            message = f'[{col}] {df.columns[int(col)]}' \
                      f' - <{val}> {df[df.columns[int(col)]].unique()[val]}'
            flash(message, "val")
    

    Thus, it would now display within the select form:

    <option> [column 1] value 1 </option>
    <option> [column 1] value 2 </option>
    <option> [column 2] value 1 </option>
    <option> [column 2] value 2 </option>