开发者

Checking for content in Django request.POST

开发者 https://www.devze.com 2022-12-11 20:32 出处:网络
I am accepting data via request.POST like this: if request.method == \'POST\': l = Location() data = l.getGeoPoints(request.POST)

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

It accepts data from a bunch of te开发者_如何学Goxt 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.


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.


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

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


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


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 .


request.POST returns a type of QueryDict (which extends the Dictionary superclass).

This means you can iterate through the keys in this dictionary (all the parameters in POST) and return false when you see one that is empty

(for key in request.POST):

if key k has invalid value (i.e. None or something else):
   return false
return true


You could also try try something like

if len(request.POST['data'])<1:
    do something if empty
else:
    do something if has data
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号