Aaron
2009-12-12 15:03:59 UTC
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.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-***@googlegroups.com.
To unsubscribe from this group, send email to django-users+***@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
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.
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-***@googlegroups.com.
To unsubscribe from this group, send email to django-users+***@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.