Trying to populate form in template

Hello,

As said in the title, i’m trying to populate a form, the initial method, with a template’s simple_tag.

The form is constructed like this:

class MyForm(forms.ModelForm) :
    class Meta :
        model = MyModel
        fields = (
            'myform_commentary' ,
            )
        widgets = {
            'myform_commentary': forms.Textarea(attrs= {'class': 'form-control'}),
        }

In context i’m giving the empty form and a list of initial dictionnaries to populate it:

from .forms import MyForm()

def main(request):
    [...]
    context = {'MyForm' : MyForm(),
    'initial_list':[{'myform_commentary':'lorem'},{'myform_commentary':'ipsum'},{'myform_commentary':'dolor'}]}

    return render(request, 'MyApp\main.html', context)

then i definied i new template tag:

@register.simple_tag
def Populate(form, initial_dict = {}):
    form.initial = initial_dict
    return form

and in the template i’m trying to generate the three forms like this :

 {% for cm in initial_list %}
        <h4>Commentary n°{{forloop.counter}}</h4>
        <form  method="POST">{% csrf_token %}
            {% Populate form=MyForm initial_dict=cm %}
            <button type="Submit" name="Submit" value={{forloop.counter}}>Enregistrer</button>
        </form>
{%endfor%}

And the result is that the first initial dict correctly populate the first form, so the template tag is working, except that then the forms n°2 and n°3 are also populate with the first initial dictionnary.

So i first checked in the template tag script by printing what it has in “form” and “initial_dict” but it correctly receive the three commentary successively. The problem is when i print the return of the function, because it return each time the form filled with the first commentary.

So i really don’t understand why the three forms displayed are all prefilled with the first commentary…
Maybe what i’m trying to do is too fast for the form to correctly populate it and only the first one is working.
I don’t know.

If you have an idea, i’m a bit confused now :sweat_smile:

thank you

It looks like you’re trying to create multiple instances of the same form on one page.

What you’re looking for in that case are Django’s formsets.

Side note, you do not want to be generating forms in the template. The template is not the right location for such work to be done. You want to create the forms (and any other data being rendered) in the view, and pass the forms to the template in the context.

Yes, this is very much different from other web frameworks. You want to absolutely minimize the amount of work done in the templates.