1

Just like the answer,I want to dynamic Load the database in the choicefield, and i had do this

queue = forms.ChoiceField(label=u'queue',choices=((x.que,x.disr) for x in Queue.objects.all()))

but it doesn't work ,i must restart the server,the field can be update.

2 Answers 2

3

You need to call the __init__ to load the data in form dynamically. For example:

class YourForm(forms.Form):
   queue = forms.ChoiceField(label=u'queue')
   def __init__(self, *args, **kwargs):
       super(YourForm, self).__init__(*args, **kwargs)
       self.fields['queue'].choices = ((x.que,x.disr) for x in Queue.objects.all()))

Reason for doing it is that, if you call __init__ in your form, it initializes an instance of a class and updates the choice list with latest data from database. For detail understanding, check here:Why do we use __init__ in python classes?

1
  • @ruddra, what if I only need the value of a single field: If I just change "Queue.ojects.all()" in your answer to "Queue.objects.values_list('region', flat=True).distinct()" then it would report error. Could you please help take a look at my question:stackoverflow.com/questions/33012590/…. Thanks in advance.
    – Héléna
    Nov 3, 2015 at 7:24
1

Use ModelChoiceField instead of ChoiceField:

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.