Django multiple Model Forms in template

43 views
Skip to first unread message

martin....@gmail.com

unread,
Jun 22, 2018, 8:19:28 PM6/22/18
to Django users

It would be highly appreciated if you could advise how the template should be modified to scale model forms as per the code below. There are around 30 item models which are the same as parent model. Also, those model forms have to be saved to database separately so I assume there should be the same amount of model forms as there are models. Thank you very much in advance and looking forward to your insights.


forms.py


from django import forms

from django.forms import modelformset_factory, ModelForm

from .models import Assumptions

 

class AssumptionsForm(ModelForm):

 

class Meta:

    model = Assumptions

    fields = ['Bad', 'Likely', 'Best']

    exclude = ()


models.py


from django.db import models

from django.forms import ModelForm

 

class Assumptions(models.Model):

 

Bad = models.FloatField(null=True, blank=True, default=None)

Likely = models.FloatField(null=True, blank=True, default=None)

Best = models.FloatField(null=True, blank=True, default=None)

 

class Meta:

    abstract = True

 

class Item1(Assumptions):

 pass

 

class Item2(Assumptions):

 pass

 

class ItemN(Assumptions):

 pass


views.py


from django.shortcuts import render

from .forms import  modelformset_factory, AssumptionsForm

from .models import Item1, Item2, Assumptions

 

model_names = [item1, item2 ... itemN]

 

def get_assumptions(request):

 

   for name in model_names:

 

    AssumptionsFormSet = modelformset_factory(name, form = AssumptionsForm,

    extra = 5)

 

    if request.method == 'POST':                  

 

        formset = AssumptionsFormSet(request.POST, prefix = str(name))

 

        if formset.is_valid():

 

            print('valid form')

 

            for form in formset:

 

                print('in for loop after valid form1')

 

                name =  form.save()

 

 

      else:

 

        formset = AssumptionsFormSet

 

        print('reached else')

 

  return render(request, 'assumptions.html', {'formset': formset})


assumptions.html


<div class="form">

{%for name in model_names%}

<form action="" method="post">

<h1>{{name}}</h1>

{% csrf_token %}

 

<h1>{{ name }}</h1>

{{ formset.management_form }}

{{ formset.non_form_errors.as_ul }}

<table id="formset1" class="form">

{% for form in formset.forms %}

 {% if forloop.first %}

 <thead><tr>

 {% for field in form.visible_fields %}

 <th>{{ field.label|capfirst }}</th>

 {% endfor %}

  </tr></thead>

  {% endif %}

  <tr class="{% cycle 'row1' 'row2' %}">

  {% for field in form.visible_fields %}

    <td>

   {# Include the hidden fields in the form #}

   {% if forloop.first %}

  {% for hidden in form.hidden_fields %}

  {{ hidden }}

  {% endfor %}

  {% endif %}

  {{ field.errors.as_ul }}

  {{ field }}

 </td>

 {% endfor %}

 </tr>

{% endfor %}

 </table>

 

 

 

<input type="submit", name={{name.prefix}}, value={{name.prefix}} />

</form>

{% endfor%}

</div>

 

alex eckert

unread,
Jun 23, 2018, 12:57:54 PM6/23/18
to Django users
This is likely not the answer you're looking for, but my two cents...

I've never been successful in writing the templates for formsets on my own, as they tend to end up looking rather clunky. I've been using this js library to help me out as it lets you set up some basic variables and modify the appearance of the form rather easily. From my understanding, the delete and add buttons don't work very well if you simply render them in the template, but this library makes them work a little better.

I've found formsets to be very frustrating so I hope you manage to do better than me!

martin....@gmail.com

unread,
Jun 23, 2018, 11:54:35 PM6/23/18
to Django users
Hi. I have changed views.py last line to this:

return render(request, 'assumptions.html', {'formset': formset,'model_names': model_names,'name': name})

As a result, it outputted more forms, however they do not save to model forms to database and raise
Validation Error ['ManagementForm data is missing or has been tampered with']

Any advise how to successfully save the model forms into database is highly appreciated.

Thank you.

Reply all
Reply to author
Forward
0 new messages