[Django]-How do I programmatically set a django choice field?

3👍

Have a look here: http://docs.djangoproject.com/en/dev/ref/models/fields/#choices

You need to set the choices attribute on the field. You can generate these choices dynamically as well when your form is getting instantiated like so:

class MyForm(ModelForm):
  def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['field_name_in_question'].choices = generate_choices_as_tuple()

generate_choices_as_tuple() will be a function that will return a tuple in the format laid out in the documentation.

👤Abid A

Leave a comment