Reputation: 39
I have this very simple form and I want that the only field must not be empty. So in the doc, required=True is the answer :
class AjouterGroupe(forms.Form):
nom = forms.CharField(required=True, label="", max_length=30, widget=forms.TextInput(attrs={'placeholder': 'Nom', 'class':'form-control input-perso'}))
This is some of my view :
Formset = formset_factory(data.form(table, 1), extra=nbajout)
if request.method == 'POST' and first:
formset = Formset(request.POST, request.FILES)
if formset.is_valid():
nbajout = 0
envoi = True
for form in formset:
print(form.is_valid())
print(form)
form.save()
form = nbAjout()
else:
formset = Formset()
In a particular case, data.form(table, 1)=AjouterGroupe.
But the main issue is that form.is_valid() is True when I validate with an empty field :/
Variable Value
csrfmiddlewaretoken 'uw1fFj9toTU3o3Il3lFW0yvt4OS31XUn'
form-INITIAL_FORMS '0'
form-MAX_NUM_FORMS '1000'
form-TOTAL_FORMS '1'
form-MIN_NUM_FORMS '0'
form-0-nom ''
Upvotes: 2
Views: 3151
Reputation: 18681
This is because Formsets
do allow blank values. If nothing is entered, it will be considered as a form that doesn't need to be added.
Try with your form on its own (not part of a formset): there, your required=True
will work fine. Also, if you'd try with a model with two fields (both set to required=True
) you'll see that an error is thrown if only one field is filled.
You should be able to play around with formset_factory
parameters like min_num=<number>, validate_min=True, extra=1
etc. to force the verification.
See also Django formset doesn't validate.
Upvotes: 4