× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Django form choices loaded from database are not updated

Viorel Stirbu
Feb 23, 2015
<p>You might have a choice field in a Django form that loads it's options from the database.</p> <pre><code>class MyForm(forms.Form):     favorite_colors = forms.ChoiceField(choices=[(color.id, color.name) for color in Color.objects.all()])</code> </pre> <p>Everything looks fine, the colors will show up, but after you update the colors in the database you will notice they are not update right away but only after you restart the application. That's because module is loaded and the form is evaluated only at application startup. A better option would be to reload the list on each request and you can do that by overriding __init__ on the form class.</p> <pre>class MyForm(forms.Form):     favorite_colors = forms.ChoiceField(choices=[])     def __init__(self, user, *args, **kwargs):         super(MyForm, self).__init__(*args, **kwargs)         self.fields['favorite_color'] = forms.ChoiceField(choices=[(color.id, color.name) for color in Color.objects.all()]) </pre> <p>That moves the loading to the point were you instantiate the form in the view.</p>
comments powered by Disqus