On Jul 31, 7:37 pm, Malcolm Tredinnick <[email protected]>
wrote:
> On Fri, 2009-07-31 at 16:31 -0700,mviamariwrote:
> > Hello,
>
> > I'm trying to make a form for data entry into my database that uses
> > ChoiceFields for foreign keys.  Obviously, the ideal choice would be
> > ModelChoiceField, however I'm not using the django ORM, so I've
> > assumed that's not going to work (I'm using Elixir/SQLAlchemy).
>
> > I originally set the choices parameter in the ChoiceField declaration
> > to be derived from a query result from SQLAlchemy (returned as an
> > array of tuples).  The problem is that the choices don't update when
> > the database changes.  They are fixed to whatever was present when the
> > server is initialized (or at least it appears to be).
>
> If you have specified the choices field as a parameter to a Field
> subclass in a Form class, then it will be evaluated whenever that Form
> class is parsed (probably at import time). That's normal Python
> behaviour.
>
> > I'm looking for suggestions/advice on to get the ChoiceField choices
> > to update when the form is the used.
>
> "Used" is probably a bit ambiguous here. It's probably easier to think
> in terms of "when an instance of the form class is created." The
> solution is to update the choices attribute on the appropriate field in
> the Form subclass's __init__() method. For example
>
>         class MyForm(forms.Form):
>            options = forms.ChoiceField()
>
>            def __init__(self, *args, **kwargs):
>               super(MyForm, self).__init__(*args, **kwargs)
>               choices = ...   # <-- create a sequence of 2-tuples
>               self.fields["options"].choices = choices
>
> You can do whatever you like to populate the "choices" variable in the
> above fragment. The only requirement is that you end up with a sequence
> of pairs which are the submitted form value and the human readable text
> for the form element.
>
> Regards,
> Malcolm

Thanks Malcom.  That appears to have worked.

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

Reply via email to