Django Newforms HiddenInput Values
Posted on | January 3, 2007 | 4 Comments
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" />
Technorati Tags: django, code, examples
Comments
4 Responses to “Django Newforms HiddenInput Values”
Leave a Reply
January 25th, 2007 @ 7:43 am
I’m loving the newforms too. thanks for the info.
June 16th, 2007 @ 12:00 pm
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.
December 13th, 2007 @ 3:30 pm
Zigarn hath saved me from much woe. Just what I was looking for!
January 5th, 2008 @ 10:56 am
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.