Add extra field to ModelForm

2,812 views
Skip to first unread message

adelaide_mike

unread,
Jul 11, 2009, 11:08:28 AM7/11/09
to Django users
Django 1.0.2. My ModelForm concerns (and is based on the table for)
advertisements for houses placed by real estate agents.

I need the agent widget (which by default is a pick list of all
agents), to be modified on the form to be either (depending on
circumstances) a non-editable preset display object, or a pick list
with a dynamically set choice of two agents.

So, I need to add extra fields to my ModelForm. Can this be done?

Thanks

Mike

Alex Gaynor

unread,
Jul 11, 2009, 11:17:03 AM7/11/09
to django...@googlegroups.com
Sure, just define a Field on the ModelForm in the same way you would on a regular Form and it will get added to the Form.

Alex

--
"I disapprove of what you say, but I will defend to the death your right to say it." -- Voltaire
"The people's good is the highest law." -- Cicero
"Code can always be simpler than you think, but never as simple as you want" -- Me

adelaide_mike

unread,
Jul 11, 2009, 6:23:22 PM7/11/09
to Django users
Thanks Alex.

A simpler way out would be if the agent field, which is a foreign key
pick list, could be caused to show only those values I determine
dynamically.

Is this possible in a ModelForm?

Mke

On Jul 12, 12:17 am, Alex Gaynor <alex.gay...@gmail.com> wrote:
> On Sat, Jul 11, 2009 at 10:08 AM, adelaide_mike <mike.ro...@internode.on.net

Shawn Milochik

unread,
Jul 13, 2009, 10:38:09 AM7/13/09
to django...@googlegroups.com

On Jul 11, 2009, at 6:23 PM, adelaide_mike wrote:

>
> Thanks Alex.
>
> A simpler way out would be if the agent field, which is a foreign key
> pick list, could be caused to show only those values I determine
> dynamically.
>
> Is this possible in a ModelForm?
>
> Mke

If I understand correctly, what would help you is to add that 'agent'
field to the exclude tuple of your model form and add another
ChoiceField, setting its 'choices' dynamically in the __init__ of your
ModelForm.

Something vaguely like this:

class ListingForm(forms.ModelForm):

agent_id = forms.ChoiceField()

def __init__(self, *args, **kwargs):
realtor = kwargs.pop('realtor')
super(ListingForm, self).__init__(*args, **kwargs)
agent_choices = [('', '--SELECT AGENT--')] + [(str(x.id),
x.name) for x in realtor.agent_set.all()]
self.fields['agent_id'].choices = agent_choices

class Meta:
model = Listing
exclude = ('agent',)

Reply all
Reply to author
Forward
0 new messages