[Fixed]-Create a list of choices automatically

1👍

Dynamic choices currently can’t be defined in the model definition so you need to pass a callable to the corresponding ChoiceField in your form.

In your case generating the rows might look like this:

def get_row_choices():
    import string
    chars = string.ascii_uppercase
    choices = zip(range(1, 27), chars)
    # creates an output like [(1, 'A'), (2, 'B'), ... (26, 'Z')]
    return choices

class SeatForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SeatForm, self).__init__(*args, **kwargs)
        self.fields['row_id'] = forms.ChoiceField(choices=get_row_choices())

Now you could use this form for your SeatAdmin like this:

class SeatAdmin(admin.ModelAdmin):
    form = SeatForm
👤arie

0👍

I am assuming here that what you really want to do is to link row and column to existing entities Row and Column. Because otherwise you would just go as it is implemented above (you already have that). But bear in mind that choices are meant to be tuples.
Check out the documentation around that:
https://docs.djangoproject.com/en/1.10/ref/models/fields/#choices.

If you want to link those to existing model classes what you are looking at are foreign keys.

👤chaos

Leave a comment