Tamper safe HiddenFields

class someInputForm(forms.Form):
    def __init__(self, protectedFields, *args, **kwargs):
        super(someInputForm, self).__init__(*args, **kwargs)
        for key, value in protectedFields.iteritems(): # For Python 2.6 just use items()
            self.fields[key] = forms.CharField(initial = value, widget = forms.HiddenInput())
            item = value
            def cleanthis(item = item): # Sometimes you have to decide if you love Python for this or not ;-)
                return item
            setattr(self, 'clean_%s' %(key), cleanthis)

# Example:
hiddenData = {'action': 'add', 'hash': '05ff2cba6e002b09288a99701ad5cfc9'}
form = someInputForm(hiddenData)

More like this

  1. Prevent form tampering of hidden fields by theju 4 years, 4 months ago
  2. Easier prefix handling for forms by gsakkis 4 years ago
  3. Complex Form Preview by smagala 5 years ago
  4. Sign a string using SHA1, then shrink it using url-safe base65 by simon 5 years, 8 months ago
  5. FieldsetForm by Ciantic 7 years ago


brooks_lt (on November 13, 2008):

Am I the only person confused by this?


aarond10ster (on November 18, 2008):

Nope... I am also scratching my head...


alexmeisel (on January 1, 2009):

I updated the documentation to clarify a few things for the people scratching their heads ... or not being very familiar how python works (setattr) and how to use django forms in a 'complicated' environment.


mark0978 (on January 13, 2009):

It creates pseudo anonymous functions that are put into the clean portion of the form for all the protected/hidden fields.

So that when they get "cleaned" they get the value that they had when they left the server, instead of the value they had when the came back from the browser.

Interesting idea, but I have to wonder, if, at the point the form is being returned from the browser, you know those values, why, did you ever send them to the browser in the first place?


alexmeisel (on April 9, 2009):

mark0978: You want to send hidden data if there is some javascript picking it up ... doing some magic with it.

I'm used to ignore those fields but I have seen a lot of django based applications which carry some state from one step to another. Hidden form fields are obviously the wrong way to do it (use sessions instead!!), but that doesn't stop people still doing it.


(Forgotten your password?)