HiddenInput for ModelChoiceField

61 views
Skip to first unread message

Aaron

unread,
Dec 12, 2009, 10:03:59 AM12/12/09
to Django users
Say I have this model:

model Foo(models.Model):
bar = models.ForeignKey(Baz)

I have a ModelForm for Foo (FooModelForm). However, instead of having
a ModelChoiceField for bar, I want a single bar object in a hidden
field that's specified when creating the FooModelForm.

my_bar = Baz.objects.get(filter)
my_foo_form = FooModelForm(bar = my_bar)

I'm not sure how to do this though. This was my first crack at it:

class FooModelForm(forms.ModelForm):
bar = forms.ModelChoiceField(queryset = Baz.objects.all(), widget
= forms.HiddenInput())

class Meta:
model = Foo

def __init__(self, *args, **kwargs):
new_bar = kwargs['bar']
del kwargs['bar'] # I get "__init__() got an unexpected
keyword argument 'bar'" if I don't do this
super(FooModelForm, self).__init__(*args, **kwargs)
self.fields['bar'].default = new_bar

When I render a form with a template, the hidden input tag has nothing
set for it's value attribute in the HTML. I also tried setting
'self.fields['bar'].default' to 'new_bar.pk', but there still wasn't a
value attribute.

Aaron

unread,
Dec 14, 2009, 9:00:01 AM12/14/09
to Django users
OK, I think I've answered my own question, though I'll need to test
it.

Instead of overriding FooModelForm's __init__(), I'd just create
create a FooModelForm with "FooModelForm (initial = {'bar':
some_bar})". I also detected some naming errors since my last post.
Reply all
Reply to author
Forward
0 new messages