Monday, May 31, 2010

Twisty Little Passages... widgets, fields, forms

I'm trying to implement a simple grade book application using a
modelformset where the students' names are READONLY and the grades are
the only thing the teacher can edit. I've been looking for sample code
to implement the readonly portion and one fellow (on another site)
suggests I use his, but he never posts sample usage code along with
it.

He suggests I use a custom widget:
class ReadOnlyWidget(forms.Widget):
def __init__(self, original_value, display_value=None):
self.original_value = original_value
if display_value:
self.display_value = display_value
super(ReadOnlyWidget, self).__init__()
def _has_changed(self, initial, data):
return False
def render(self, name, value, attrs=None):
if self.display_value is not None:
return unicode(self.display_value)
return unicode(self.original_value)
def value_from_datadict(self, data, files, name):
return self.original_value

But I can't figure out how to set the original_value in my
application.
The "obvious" choice like:
class GradeForm(ModelForm):
student = forms.CharField(max_length=50,
widget=ReadOnlyWidget(instance))
doesn't work as I'm fairly sure instance isn't set here or if it is
how I can invoke it so it does the right thing in a modelformset.

The less obvious choice of setting it from within the form's __init__
function is currently beyond my ability as I do not understand the
code flow through here and am not sure how to instantiate the widget
from within the form's __init__ function.

Can someone point me to a good source of documentation at this level
of detail?

Thanks

Mike

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment