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.

ruddra
  • 50,746
  • 7
  • 78
  • 101
junfeng
  • 33
  • 3

2 Answers2

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?

Community
  • 1
  • 1
ruddra
  • 50,746
  • 7
  • 78
  • 101
  • @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:http://stackoverflow.com/questions/33012590/django-init-takes-at-least-2-arguments-for-dynamic-drop-down-list-function. Thanks in advance. – Héléna Nov 03 '15 at 07:24
1

Use ModelChoiceField instead of ChoiceField:

catavaran
  • 44,703
  • 8
  • 98
  • 85