Rico
Rico

Reputation: 6052

Comparing Django POST data

I'm expecting POST data and want to create a custom dictionary to use when creating a form based on what is POSTed. I seem to be running into problems trying to compare what is in the POST data. I'm using Django 1.4 with Python 2.7 on Ubuntu 12.04.

Suppose I have a POST field called return_method that will tell me what type of return method the client expects. Either they will send the value post or get. Now, I want to create the dictionary differently based on which value I get.

if (request.POST.get('return_method') == 'get'):
    cust_dict = { 'key1' : value1,
                  'key2' : value2,
                  'key3' : value3,
                }

elif (request.POST.get('return_method') == 'post'):
    cust_dict = { 'key1' : value1,
                  'key2' : value2,
                  'key3' : another_value,
                }

This isn't working. I'm populating the field with get and neither dictionary is getting created.

What would you suggest I do instead?

EDIT: It appears my problem was that my changes were not being updated on the Django server. (had to restart Apache)

Upvotes: 0

Views: 253

Answers (2)

Shawn Chin
Shawn Chin

Reputation: 86924

Here's how I would approach it.

custom = {
  "get" : {
    'key1' : value1,
    'key2' : value2,
    'key3' : value3,
  },

  "post" : {
    'key1' : value1,
    'key2' : value2,
    'key3' : another_value,
  },
}

try:
    cust_dict = custom[request.POST.get('return_method').strip()]
except KeyError:
    # .. handle invalid value

That said, there's no reason why your version won't work. Have you check the value you're seeing in request.POST.get('return_method')? Perhaps there are white-spaces in the values that's foiling your string matching (note the .strip() in example code above).

Upvotes: 1

dm03514
dm03514

Reputation: 55972

 cust_dict = { 'key1' : value1,
               'key2' : value2,
             }


if request.POST.get('return_method') == 'get'): 
  cust_dict['key3'] = value3
elif request.POST.get('return_method') == 'post):
  cust_dict['key3'] = another_value

if key3 is not being added to your cust_dict then the value of return_method is neither get nor post

Upvotes: 1

Related Questions