= CookBook - Manipulator With Hidden Fields = == Description == I needed to present a form to allow a user to create a new object. However, some fields in the object were already known by the system (such as the user who was adding the object). Rather than presenting these fields to the user, I created a custom manipulator that allowed me to hide them. The example will be a user creating a new message. == Code == Here's a simple Message model as an example: {{{ #!python class Message(meta.Model): fields = ( meta.CharField('title', maxlength=255), meta.TextField('body'), meta.DateTimeField('postDate', auto_now_add=True), meta.ForeignKey(auth.User), ) }}} Here's the custom manipulator that allows us to hide the user and project fields. It inherits from the model's pre-made !AddManipulator, the iterates over the fields replacing some of them with a formfields.!HiddenField {{{ #!python class MessageManipulator(messages.AddManipulator): def __init__(self): # Set everything up initially using the built in manipulator messages.AddManipulator.__init__(self) newFields = [] # Iterate over all the fields looking for the ones I want to hide, # and replacing them with HiddenFields for field in self.fields: if field.field_name in ('user_id',): field = formfields.HiddenField(field.field_name, field.is_required, field.validator_list) newFields.append(field) self.fields = newFields }}} Here's the view code: {{{ #!python def addMessage(request): manipulator = MessageManipulator() if request.POST: newData = request.POST.copy() errors = manipulator.get_validation_errors(newData) if not errors: manipulator.do_html2python(newData) newMessage = manipulator.save(newData) return HttpResponseRedirect(newMessage.get_absolute_url()) else: errors = {} # Add the the data that you already know and don't want to burden # the user with here. newData = {'user_id': request.user.id,} form = formfields.FormWrapper(manipulator, newData, errors) t = template_loader.get_template('addMessage') c = Context(request, {'form': form,}) return HttpResponse(t.render(c)) }}} Here's part of the template code. {{ form.user_id }} places the hidden field in the form. It will be populated with the correct data because we set that in newData above. Title and Body are other fields defined in the Message model. messages.!AddManipulator took care of populating those correctly. {{{