Defining the Json

There’s a new project in town.  We’re trying to hook up a homepage contact form to an existing Django-driven database via AngularJS (that’s a lot of buzzwords!).  The form has a few required fields, and some more optional fields.  The first couple tests didn’t work- turns out the culprit was the models- the non-required fields didn’t have the blank=True, null=True settings enabled, so the form was getting blocked there.

As an aside- troubleshooting a form submission using Django and Angular can be tricky.  Normally, Django gives you a nice, long error page with what went wrong.  It’s not always easy to decipher, but it always at least points you in the right direction.  But when sending it back and forth via an $http request, it can be more difficult to get the actual issue.  I settled for logging the on the failure callback function to the console- that way I could at least see where in the chain I was going wrong.

So, I changed the models to allow blank entries on those fields that aren’t required.  Boom- no more error message.  Status 200, data being properly sent, good to go!

Not quite- now everything said it was working, but nothing was being saved to the test database.  I tried changing the function within my Angular controller.  I was really proud of my solution originally- to loop through all the form fields dynamically on submission, using a for-in (with the hasOwnProperty check) loop to get all the form ids and values (so if we want to change the form, we don’t have to change the Angular function- it will just get the new fields).  But maybe that was an issue (though it didn’t throw any errors), so I switched and manually grabbed the value of each form field.

Still no luck.  To make a long story short (too late), any field left blank when the form was submitted was being registered as ‘undefined’.  JSON (the format data is transferred in via an $http request) doesn’t like undefined, and was failing whenever it saw that in the object.  The solution was easy- I reinstated the for-in loop and added a check on each item (data is an empty object initialized higher up in the code that would be passed as data in the $http call):

for(var item in form) {
if(form.hasOwnProperty(item) {
data[form[item].id] = form[item].value || 'Info Not Submitted';

This prevented any undefined values from being submitted via the form, and everything started working.  Next time: I extol the virtues of Django’s built in JSON encoding functions.  They’re really great!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s