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
thank you