September 3, 2010

Django Newforms HiddenInput Values

I really like Django’s newest module for forms, “newforms”. Despite its currently lacking documentation, it is well worth learning.

It feels much more “Pythonic” than the old manipulator-based method. Less magic is going on, and less constant reference to the manual is needed. However, I found myself beating my head against one undocumented, and also lacking any test case feature.

How to get newforms “hidden” fields to have a value

I’ll spare you the trials, tribulations and shrewd guessing, here’s the answer. Put the value in the widget attributes, not the form field.

For example, here I want to put in the object id for a die roll in my invisiblecastle django rewrite


def __init__(self, *args, **kwargs):
    [...]
    rollwidget = =forms.HiddenInput(attrs={'value' : roll.id})
    self.fields['rollid'] = forms.IntegerField(widget=rollwidget, required=False)

When I later print the form, I get something like this:


<input type="hidden" name="rollid" value="4" id="id_rollid" />

[tags]django,code,examples[/tags]

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Related posts:

  1. Django Formatter Mixin Class I've always disliked having to write __repr__ methods for my...
  2. Helpful Django utilities and links Two simple links which have been very helpful in doing...
  3. Django Magic Removal, this time for real Despite my earlier initial successes using the Django Magic-Removal Branch,...
  4. A Django Killer App – Web Table Data Yet another great use for Django is to make trivial...
  5. Stats on a larger Django project A Django website that took (a lot) more than 20...

About Bruce Kroeze

Comments

  1. rezzrovv says:

    I’m loving the newforms too. thanks for the info.

  2. Zigarn says:

    You can dynamically define initial value of fields at form creation : http://www.djangoproject.com/documentation/newforms/#dynamic-initial-values

    class myForm
    rollid = forms.IntegerField(required=True, widget=forms.HiddenInput())

    [...]

    form = myForm(initial={‘rollid’, roll.id})

    And you will get the same.

  3. david says:

    Zigarn hath saved me from much woe. Just what I was looking for! :)

  4. Steven says:

    It get’s even easier with ModelForms. Just use:

    from django import newforms as forms
    from django.newforms.models import ModelForm
    from models import Bookmark

    class BookmarkForm(ModelForm):
    id = forms.IntegerField(required=False, widget=forms.HiddenInput())
    class Meta:
    model = Bookmark

    And it all just works.

Speak Your Mind

*