[Python] Django: Change formset error message(s)

Discussão em 'Python' iniciado por Stack, Março 5, 2025.

  1. Stack

    Stack Membro Participativo

    Hello fellow programmers,

    I would like to change the min_num error message of a formset.

    My code creates a formset using an inlineformset_factory:

    formset_clazz = inlineformset_factory(MyParentModel, MyModel, MyModelForm, can_delete=True, min_num=1, validate_min=True)
    formset = formset_clazz(data=request.POST)
    print(formset._non_form_errors)
    if formset.is_valid():
    print("yay!")
    else:
    print("nay!")
    return render(request, "mytemplate.html", {'formset':formset})


    In the template I render the non_form_errors:

    {% if formset.non_form_errors %}
    <ul>
    {% for error in form.non_form_errors %}
    <li>
    {{ error }}
    </li>
    {% endfor %}
    </ul>
    {% endif %}


    The min_num validation works as intended and shows the error message Please submit 1 or more forms., when a user removes all forms and submits the formset.

    My question is: How do I change the error message?

    From [0] I learned, that it is stored in formset._non_form_errors, but without a way to override the too_few_forms [1] (ctrl-F validate_min) code's message. The BaseFormSet class itself uses ngettext to translate the message, but I do not really want to setup internationalization just for this (or is that easy and straight-forward?).

    Is there a more convenient way to achieve my goal?

    [0] Django: Displaying formset errors correctly

    [1] https://docs.djangoproject.com/en/2.0/_modules/django/forms/formsets/#BaseFormSet

    Continue reading...

Compartilhe esta Página