tags:

views:

158

answers:

1

Is there a recommended way of using Django to clean an input string without going through the Django form system?

That is, I'm writing code that delivers form input via AJAX so I'm skipping the whole Form model django offers. But I do want to clean the input prior to submission to the database.

+8  A: 

Django Form models aren't just about rendering forms, they're more about processing and sanitizing form (GET/POST) input, which is what you want to do. When the POST or GET data from your AJAX request reaches your server it's essentially indistinguishable from form data. I would advocate creating a Form model that is a model of your AJAX request.

Think of an example POST:

POST /login.jsp HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

userid=joe&password=guessme

That could have come from an AJAX request OR a form, by the time it hits your server it doesn't really matter! Sure they're called Form models because that's usually where GET or POST data comes from, but it doesn't have to be from a form :)

If you create a Form model to represent your AJAX request you get all the hooks and sanitization that come with it and it's all a little more "django-esque".

Update regarding your comment:

I imagine you'd have multiple form classes. Obviously I don't know how your system is designed, but I'll provide what advice I can.

Like you said, you'll be using this to sanitize your data so you'll want to define your Form classes based on the data you're sending. For example, if I have an AJAX request that submits a comment with Name, Email and CommentBody data that would be one Form class. If I have another AJAX request that posts a new article that sends Title, Author and ArticleBody that would be another Form class.

Not all your AJAX requests will necessarily need a Form, if you have an AJAX call that votes up a comment you probably wouldn't treat that as a form, since (I'm guessing) you wouldn't need to sanitize any data.

Matt Baker
Matt, my system uses AJAX extensively to update data in the database. Would you recommend creating a derived form class for each ajax request or, if possible, a general use ajax derivation that handles any inputs.
Karim
I edited my answer in response, it was easier than trying to stuff it in a comment :)
Matt Baker
+1: Forms are for cleaning input. "2. Check submitted data against a set of validation rules." We use Forms to validate our web services input.
S.Lott
Okay, so it sounds like the django way of doing things would be to create a form for each ajax posting that requires validation. Seems heavy-handed but a clean/organized way of doing things.
Karim