So I'm using a dynamic formset within django:
https://github.com/elo80ka/django-dynamic-formsetI'm using it to render a page with a form (say, a pizza) and a formset (say, a set of toppings). Because the number of toppings isn't determined, I want to use a dynamical formset.
Right now, I have the page display one instance of topping form, with a button to add another instance, which is added with the javascript found in the github repo (and as a attachment).
Only I have a problem: When I fill in the form for one topping, and then add another topping, all the radiobuttons get reset so the data from the first topping is lost.
Does anyone see what goes wrong here? This is my code, simplified (I actually have a lot more fields for the form and subset, all choicefields needing radiobuttons, so this is quite a big issue for me).
models.py:
class Pizza(models.Model):
name= models.CharField(max_length=55)
pricerange=models.CharField(max_length=55, choices=PRICERANGE_CHOICES)
class Topping(models.Model):
pizza = models.ForeignKey(Pizza)
number = models.IntegerField(null=True, blank=True)
name=models.CharField(max_length=55, choices=TOPPINGNAME_CHOICES)
forms.py:
class PizzaForm(forms.ModelForm):
class Meta:
model = Pizza
fields = ['name', 'pricerange']
pricerange= forms.ChoiceField(required=True,widget=forms.RadioSelect(),choices=PRICERANGE_CHOICES)
class ToppingForm(forms.ModelForm):
class Meta:
model = Topping
fields = ['number', 'name'
]
number = forms.IntegerField(required=True)
name = forms.ChoiceField(required=True,widget=forms.RadioSelect(),choices=TOPPINGNAME_CHOICES)
ToppingFormset = formset_factory(ToppingForm, max_num=8)
form.html:
<script type="text/javascript" src="/static/pizza/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/static/pizza/jquery.formset.js"></script>
<script type="text/javascript">
$(function() {
$('.ToppingForm').formset();
})
</script>
<style type="text/css">
.add-row {
padding-left:18px;
background:url(/static/arts/images/add.png) no-repeat left center;
}
.delete-row {
display:block;
margin:6px 0 0 0;
padding-left:18px;
background:url(/static/arts/images/delete.png) no-repeat left center;
}
.dynamic-form { padding: 5px 15px; }
</style>
<form method="post" action=""> {% csrf_token %}
{{ form.non_field_errors }}
{{ form.pricerange}}
<div class="ToppingFormset">
{% for form in formset.forms %}
<div id=" {{ form.prefix }}-entry" class="ToppingForm">
<table class="t03" style="width:100%">
<tr><td colspan="8">{{ form.name.label_tag }} {{ form.name.errors }}</td></tr>
<tr>
<td>{{ radio }}</td>
{% endfor %}
</tr>
</table>
</div>
{% endfor %}
</div>
<p>{{ formset.management_form }}</p>
<input type="submit" value="Volgende"/>
</form>