Modifiez le nombre de formulaires enfants de Companion par le nombre de commandes saisies (unités).
Je ne sais pas comment faire, alors je vais l'essayer de force. ::
if request.method == "POST":
form = OrderForm(user=request.user,
ticket=ticket, data=request.POST)
#: Order(commande)
is_form_valid = form.is_valid()
#: Companion (Personne accompagnante)
formset = create_companion_formset(
request, order=form.instance)
is_formset_valid = formset.is_valid()
number = int(form.cleaned_data.get('units', 1))
if number != len(formset.forms):
#:Parce qu'il y a eu un changement dans le nombre....
is_formset_valid = False
old = formset
#:Recréez l'ensemble de formulaires avec un nouveau numéro
formset = create_companion_formset(None, extra=number)
#:faire une copie
for i in range(min(number, len(old.forms))):
formset.forms[i] = old.forms[i]
if is_form_valid and is_forset_valid:
form.save()
formset.save()
#:.....
Saisie obligatoire du formulaire enfant ajouté:
class OrderCompanionFormset(BaseInlineFormSet):
def clean(self):
for i in range(self.total_form_count()):
if not self.forms[i].has_changed():
_errs = self.forms[i].error_class(
[_("Form must be filled.")])
self.forms[i].errors['__all__'] = _errs
Usine Formset:
def create_companion_formset(request, order=None, extra=1, *args, **kwargs):
'''Créer un ensemble de formulaires compagnon'''
kwargs['form'] = CompanionForm
kwargs['can_delete'] = False
kwargs['formset'] = OrderCompanionFormset
#:Ordinaire
if request and request.method == "POST":
formset = inlineformset_factory(
Order, Companion,
*args, **kwargs)(request.POST, instance=order)
else:
formset = inlineformset_factory(
Order, Companion, extra=extra,
*args, **kwargs)(instance=order)
return formset
Le message _errs apparaît dans non_form_erros:
{% for form in formset %}
<h4>Personne accompagnante</h4>
{% if form.non_form_errors %}
<div class="alert alert-error">{{ from.non_form_error.as_text }}</div>
{% endif %}
....
{% endfor %}
Recommended Posts