Reputation: 8647
I know is_valid()
on a bounded form checks if all required data is entered. This is not what I want. I want to check if any field was filled on the form.
Any ideas?
Elaborating:
I want to give the user the choice of not filling in the form at all. However, if they attempt to fill it in (ie: changed a value in a field from it's initial value---usually empty value), I want to validate it.
The view would be something like this:
def get_opinion(request):
if request.method == 'POST':
f = OpinionForm(request.POST)
if form_is_blank(f):
return HttpResponseRedirect(reverse('thank_you_anyway'))
elif f.is_valid():
#Process here
return HttpResponseRedirect(reverse('thanks_for_participating'))
else:
initial = {'weekday': date.today().strftime('%A')}
f = OpinionForm(initial=initial)
return render_to_response(
'get_opinion.html',
{'form': f,},
RequestContext(request)
)
What I want is the form_is_blank()
part.
Upvotes: 20
Views: 14570
Reputation: 8647
Guess I have to answer my own question.
Apparently, there's an undocumented Form
function: has_changed()
>>> f = MyForm({})
>>> f.has_changed()
False
>>> f = MyForm({'name': 'test'})
>>> f.has_changed()
True
>>> f = MyForm({'name': 'test'}, initial={'name': 'test'})
>>> f.has_changed()
False
So this would do nicely as the replacement for form_is_blank()
(reverted of course).
Upvotes: 30
Reputation: 22248
You should set required=False for all fields in the form and override the clean
method to do custom validation. See the current documentation for more.
Upvotes: 3
Reputation: 1970
To get this functionality work for subset of Forms used in the actual <form> tag you also need to define
class YourForm(forms.ModelForm):
def full_clean(self):
if not self.has_changed():
self._errors = ErrorDict()
return
return super(YourForm, self).full_clean()
so when the user is prompted to fix validation errors it doesnt display errors from the forms which you want to validate only if some value isn't blank (or default).
Upvotes: 4
Reputation: 70059
If you have put required=True
in your forms field or in the model blank=False
so is_valid()
should return False.
Upvotes: 1