Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to check if the user left all fields blank (or to initial values)?

Tags:

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.

like image 971
Belmin Fernandez Avatar asked Jan 01 '11 00:01

Belmin Fernandez


People also ask

How do I check if a field is empty in Django?

if not form. data['first_name']: checks for None or '' an empty string or False come to that.

What is NULL and blank in Django?

null is purely database-related, whereas blank is validation-related(required in form). If null=True , Django will store empty values as NULL in the database . If a field has blank=True , form validation will allow entry of an empty value . If a field has blank=False, the field will be required.

Why we use NULL true in Django?

If a string-based field has null=True , that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it's redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.


1 Answers

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).

like image 77
Belmin Fernandez Avatar answered Oct 26 '22 06:10

Belmin Fernandez