On 10/27/06, Russell Keith-Magee <[EMAIL PROTECTED]> wrote:
>
> On 10/26/06, Ice9 <[EMAIL PROTECTED]> wrote:
> >
> > Hi, I'm kinda new to django, and I ran into a problem
> > I'm making a cutom form, and one of the field I want it to be
> > SelectField. the problem is I dont want to hard code the choices in, I
> > want to generate a set of choice I can use from the data i already
> > have.
> > For example, I have a lot of polls, and I want the choices to be all
> > the polls posted by user root. How would I come to do that?
>
> Sounds like you need 'limit_choices_to' on a Foreign Key. Add a
> Foreign Key on Choices to the Poll model; use the limit_choices_to
> argument on the ForeignKey defintion to filter out those choices you
> don't want.
>

Russell's answer is your best option in this case and is also cleaner.
However, if you still want to know how to generate the choices list
for your SelectField, you can do something like this:

class MyManipulator(forms.Manipulator):
    def __init__(self):
        filtered_data = MyModel.objects.filter(... some condition...)
        my_choices = [(obj.id, obj) for obj in filtered_data]

        self.fields = (
            forms.SelectField(field_name='name', choices=my_choices),
        )

Basically you use a list generation expression to generate a list of
tuples, each tuple must contain two elements, the first element is the
choice value (e.g. the id of the object) and the second element is the
label that you want to display in the select field for that value (in
this example we assume that obj has an appropriate __str__() method).

Hope it helps.

Regards,
Jorge

--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to