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]
Related posts:
- Django Formatter Mixin Class I've always disliked having to write __repr__ methods for my...
- Helpful Django utilities and links Two simple links which have been very helpful in doing...
- Django Magic Removal, this time for real Despite my earlier initial successes using the Django Magic-Removal Branch,...
- A Django Killer App – Web Table Data Yet another great use for Django is to make trivial...
- Stats on a larger Django project A Django website that took (a lot) more than 20...
I’m loving the newforms too. thanks for the info.
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.
Zigarn hath saved me from much woe. Just what I was looking for!
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.