views:

298

answers:

4

I feel like such a n00b asking this question but it's late and I'm tired. ;)

I am accepting data via request.POST like this:

     if request.method == 'POST': 
         l = Location() 
         data = l.getGeoPoints(request.POST) 
         appid = settings.GOOGLE_API_KEY 

         return render_to_response('map.html',  
                                    {'data': data, 'appid': appid}, 
                                    context_instance=RequestContext(request)) 

Pretty basic stuff. It accepts data from a bunch of text input boxes called "form-0-location" all the way up to "form-5-location".

What I want to add in is a check to make sure that request.POST contains data in any of those input fields. I think my problem is that I do not know the correct terminology for describing this in Django. I know how to do it in PHP: look inside $_POST for at least one of those fields to not be empty, but I can't seem to find the right answer via searching for google.

If I don't find any data in those input fields, I want to redirect the user back to the main page.

+2  A: 

With Django request objects, the POST data is stored like a dictionary, so if you know the keys in the dictionary, you can search for them and check if they're empty or not. Check out these two links for more detail:

http://docs.djangoproject.com/en/dev/ref/request-response/#attributes http://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects

And, for example, when you have your request object, and you know you have a key/var called 'form-0-location', you could do:

if request.POST.get('form-0-location'):
    print 'field is not None >> %s' % request.POST.get('form-0-location'')
kchau
+5  A: 

Have you thought about using Django's Forms?? You can mark fields as "required" when defining a form and Django will take care of validating if said fields have data in them upon submission. They also do other kinds of validation.

Rishabh Manocha
That's a good suggestion! Maybe look into ModelForms on djangoproject.com
kchau
I also recommend this approach :)
Jiaaro
A: 

I second the suggestion to use Django Forms. Why not take advantage of Django Forms when you are using Django?

Design a quick form that matches the fields you currently have on the page. Load the form with request.POST data, and use form.is_valid() to determine whether the form is valid or not .

ayaz
A: 
if request.method == 'POST' and request.POST:
       # Process request

request.POST will be false if the request does not contain any data.

Mayuresh