Reputation: 2002
What is the best way to build a validator that checks for an empty value (i.e. empty string) in a formset using django.forms.formsets.formset_factory ?
What I'm using now is, first the forms.py:
from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
class UrlsForm(forms.Form):
def validate_contains_something(value):
if value == " ":
raise ValidationError(u'(link)value: "%s" is empty' % value)
my_url = forms.URLField(required=True,
max_length=200,
label = '',
widget=forms.TextInput(
attrs=
{
'placeholder':'< enter url here >',
'size':75,
'class':'data',
}),
validators=[validate_contains_something,
URLValidator,]
)
Then shell commands:
from django.forms.formsets import formset_factory
from doc_select_new.forms import UrlsForm
from django.forms.formsets import BaseFormSet
UrlsFormSet = formset_factory(UrlsForm, formset=BaseFormSet, validate_max=True)
data = { 'form-INITIAL_FORMS': '0',
'form-MAX_NUM_FORMS': '1000',
'form-TOTAL_FORMS': '3',
'form-0-my_url': '',
'form-1-my_url': 'http://www.google.com/',
'form-2-my_url': 'https://www.djangoproject.com/',
}
formset = UrlsFormSet(data)
valid_or_not = formset.is_valid()
Which gives no error for form-0-my_url. What am I doing wrong? Or how can you let the validator for checking '' go wrong and deliver an error?
Upvotes: 0
Views: 198
Reputation: 373
Extra forms (dynamically added ones) can be empty in django. In shell this is simulated by 'form-INITIAL_FORMS'
data parameter - as it's 0, django thinks all the 3 forms are extra forms. Setting it to 1 will tell django to validate the first form.
This behavior is due to empty_permitted
form argument. So another way is to set it to False
. It will force the validation for all the forms:
class UrlsForm(forms.Form):
def __init__(self, *args, **kwargs):
super(UrlsForm, self).__init__(*args, **kwargs)
self.empty_permitted = False
Upvotes: 2