views:

269

answers:

3

I'm using the Django Form Validation Framework on AppEngine (http://code.google.com/appengine/articles/djangoforms.html), like this:

data = MyForm(data=self.request.POST)
  if data.is_valid():
    entity = data.save(commit=False)
    entity.put()

I wonder if there's a way to preprocess the POST data (strip out malicious code, HTML etc.) before storing it. It seems that any form validation library should offer something like that, no?

Thanks

Hannes

A: 

Yes, of course. Have you tried reading the forms documentation?

http://docs.djangoproject.com/en/dev/ref/forms/validation/

Daniel Roseman
+2  A: 

Short answer:

forms.is_valid() auto populates a dictionary forms.cleaned_data by calling a method called clean(). If you want to do any custom validation define your own 'clean_filed_name' that returns the cleaned field value or raises forms.ValidationError(). On error, the corresponding error on the field is auto populated.

Long answer:

Refer Documentation

Lakshman Prasad
A: 

In addition to the answers above, a different perspective: Don't. Store the user input with as little processing as is practical, and sanitize the data on output. Django templates provide filters for this - 'escape' is one that escapes all HTML tags.

The advantage of this approach over sanitizing the data at input time is twofold: You can change how you sanitize data at any time without having to 'grandfather in' all your old data, and when a user wants to edit something, you can show them the original data they entered, rather than the 'cleaned up' version. Cleaning up data at the wrong time is also a major cause of things like double-escaping.

Nick Johnson