[Django]-Add an "empty" option to a ChoiceField based on model datas

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()] 
πŸ‘€r-mean

Leave a comment