Saturday, June 26, 2010

Custom widgets in Model Formsets

I am trying to use custom widgets in a model formset. I have tried to
achieve this by first defining the custom widget, then a form that
uses this widget, then passing this form as an argument to
modelformset_factory().

I don't think something is working right because if I check the type
of the form objects in my formset, the objects are my own custom
SliderInputs; however, when the very same formset is rendered, it
renders like the default widget. They don't render with any of the
content that I have added to the render method of SliderInput.

Below is the shell session demonstrating that I have SliderInput
widgets, then the actual class code that defines these.

I am using Django 1.1.1.


>>> from fd.access.models import Flavor, Recipe
>>> from fd.access.forms import WeightSliderForm
>>> from django.forms.models import modelformset_factory
>>>
>>> flavor = Flavor.objects.all()[1]
>>>
>>> RecipeFormSet = modelformset_factory(Recipe, form=WeightSliderForm)
>>> recipe_formset = RecipeFormSet(queryset=flavor.recipe_set.all())
>>>
>>> for recipe_form in recipe_formset.forms:
... print recipe_form.Meta.widgets
...
{'amount': <fd.access.widgets.SliderInput object at 0x24b2a50>}
{'amount': <fd.access.widgets.SliderInput object at 0x24b2a50>}
{'amount': <fd.access.widgets.SliderInput object at 0x24b2a50>}
{'amount': <fd.access.widgets.SliderInput object at 0x24b2a50>}
{'amount': <fd.access.widgets.SliderInput object at 0x24b2a50>}
>>>

#######################################

class SliderInput(forms.widgets.TextInput):
"""
A slider widget to include in your form
"""

def render(self, name, value, attrs):
attributes = attrs
attributes['type'] = 'hidden'

res = super(SliderInput, self).render(name, value, attrs =
attributes)
res += '<div class="slider-wrapper">'
res += '<div id="%s_slider_value" class="slider-value">%d</
div>' % (name, value)
res += '<div id="%s_slider_unit" class="slider-unit"></div>' %
name
res += '<div id="%s_slider" class="slider"></div>' % name
res += '</div>'
return res

class Media:
css = {'screen':('/media/css/widgets/slider.css',)}
js = ('/media/js/widgets/slider.js',)

class WeightSliderForm(forms.ModelForm):
class Meta:
model = Recipe
fields = ['amount']
widgets = {
'amount': SliderInput(attrs={
'max':'1000',
'min':'0',
'step':'.001',
'unit':'%',
}),
}

--
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.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate