Testing Django Forms that Contain a MultipleChoiceField

It’s pretty simple. Just return a Python list of values:

data = {
    'a_field': u'1',
    'a_multiple_choice_field': ['achoice', 'another_choice']
}
response = client.post(view_url, data)
Advertisements

Pretty Print Django POST Data in Python Logger

Due to customer requirements, I have a webpage with several forms, and dynamic formsets that are built on the client side using jquery formset. Kind of reminds me of the Simpsons episode where Homer designs a car. But here at ROI Technologies LLC, we are not girly men. We laugh in the face of complexity. And every once in a while complexity bites us in the ass.

Obviously,┬áthe best solution is to write extensive tests. Unless of course you include costs in your calculation of your “best” metric. An alternative to automatic testing is using the Python logger to gather the info you will need to quickly fix a bug if one is encountered. That’s what this post is about.

Back to my Homer page, as you can imagine, the POST data is extensive. To output it in a readable format in the logs, use json. Like this

try:
    is_valid = my_form.is_valid()
except:
    # Grab the data to fix the bug
    logger.exception('Got exception while validating form:')
    logger.debug('Here is the post data:\n %s', json.dumps(request.POST, indent=4, sort_keys=True))
    raise #  back to crashing

That first logger line in the exception handler, prints that message along with the traceback! The second logger line uses json to pretty print the Django POST data. Happy debugging.