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
You can do it in full_clean
method of your formset class. Not pretty, but works.
class CheeseStickFormset(BaseFormSet):
def full_clean(self):
super(CheeseStickFormset, self).full_clean()
for error in self._non_form_errors.as_data():
if error.code == 'too_many_forms':
error.message = "Please eat %d or fewer cheese sticks." % self.max_num
if error.code == 'too_few_forms':
error.message = "Please eat at least %d cheese sticks." % self.min_num
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With