Matthias Pschorr
Matthias Pschorr

Reputation: 53

How to set Field attributes in jinja 2 loop

I am quite new to programming and I need your help. I have a field list of float fields where each one should display a different default value.

I want to change the default attribute by iterating in my template but it's not working.

<div class="form-group">
            {% for entry in form.pde_parameters %}
            {% set entry.default=pde_parameter_value_list[loop.index0]%}
            {{ pde_parameter_list[loop.index0] }}
            {{ entry.hidden_tag() }}
            {{ render_field(entry.parameter_value) }}
            {% endfor %}

</div>
class NewModelParameterMaskForm(FlaskForm):
    parameter_value = FloatField("")

class Solution(FlaskForm):
    pde_parameters = FieldList(FormField(NewModelParameterMaskForm), min_entries=1)
    sde_parameters = FieldList(FormField(NewModelParameterMaskForm), min_entries=1)

I get this error message:

jinja2.exceptions.TemplateRuntimeError: cannot assign attribute on non-namespace object

Upvotes: 5

Views: 8781

Answers (3)

KT.
KT.

Reputation: 11430

Just as with the dict.update suggestion above, it seems to be possible to trick Jinja into setting attributes by simply calling __setattr__ on the object:

{% set _ = obj.__setattr__('fieldname', 'value') %}

Upvotes: 4

Nicholas Reis
Nicholas Reis

Reputation: 168

I was receiving the same error. The solution I found would look similar to this in the question's case:

{% set update_result = entry.update({'default': pde_parameter_value_list[loop.index0]}) %}

Then ignore the update_result variable and use the entry normally.

It seems Jinja doesn't allow setting directly the value of a field/property inside an object. However, if these are dictionaries or lists, you can use methods like update or append since they change the object internally.

Upvotes: 4

Nick K9
Nick K9

Reputation: 4653

You need to populate the form before you pass it to Jinja, not inside your template.

def show_solution():
    form = Solution(request.form)

    if form.validate_on_submit():
        # Use form values
        return redirect(url_for('done'))

    for s in solutions(): # Fetch your solutions from somewhere
        form.pde_paramaters.append_entry({'parameter_value': s.float_value})

    return render_template('solution.html', form=form)

Upvotes: 0

Related Questions