Saturday, August 16, 2008

Forms, Helpers, and Views, Oh My!

Views do three things: take in the request, do some logic, push out the response. I had a difficult time figuring out how I was going to use views and the new newforms forms recently added to django. My major concern was that I wanted to have all data validation handled in one place (which newforms is great for), but I wanted to be able to process information that might not have come from a browser session (which newforms sucks for). I went back and forth, but finally decided on the following system.

All form data will come in as a newforms form. This is easy for webpage submits, but may require a little movement of data when stuff starts coming in through REST or webservices or something. The form handles validation and is pushed of to a helper method that does further validation and handles data transactions. This way both the site views and web services can operate with these helpers. Finally, the view sends back the reply, either a reload of the page, and redirect to a new page, or renders a template.

When looked at this way, testing became much easier, too. I test each view pretty much 3 times. 1 test is for the form, making sure valid forms are valid, and invalid forms are invalid. Another test is of the helper, that it validates the form correctly and handles the data properly, moving, saving, updating or not as it should. Finally, I test the view using django's test client. I like the test client system. It is very easy to use to test results and processes.

The nice thing about working with views is that I still don't have to worry about how it will look. I just test that for certain input (usually data provided to a form, or a dict) I get the expected output (status code, template rendered, and the correct data in the template's context). Easy!

Using this method I have created and tested the views for user registration, login, avatar creation, avatar selection, game map, and movement. I'm currently working on some views for other functions of the main game area: Message viewing, character profile viewing, and the fun abilities. I still need to do some inventory and equipment and equiping views, plus some things I've probably not even thought about yet but that need to be done for Stoneage.

Stay tuned.