10π
An easy answer is to do:
field = forms.ChoiceField(choices=[[0, '----------']] + [[r.id, r.name] for r in Model.objects.all()])
Unfortunately, your approach is flawed. Even with your βworkingβ approach, the field choices are defined when the form is defined, not when it is instantiated β so if you add elements to the Model table, they will not appear in the choices list.
You can avoid this by doing the allocation in the __init__
method of your Form.
However, there is a much easier approach. Rather than messing about with field choices dynamically, you should use the field that is specifically designed to provide choices from a model β ModelChoiceField
. Not only does this get the list of model elements dynamically at instantiation, it already includes a blank choice by default. See the documentation.
1π
Since this question and its answer almost solved a problem I just had Iβd like to add something. For me, the id had to be empty because the model didnβt recognise β0β as a valid option, but it accepted empty (null=True, blank=True). In the initializer:
self.fields['option_field'].choices = [
('', '------')] + [[r.id, r.name] for r in Model.objects.all()]
- [Django]-IPN delivery failed. HTTP error code 403: Forbidden
- [Django]-Django Import Class From models.py