Aamu
Aamu

Reputation: 3601

Create a list of choices automatically

I am making an on-line theater booking app in django (v1.10.5) and python.

models.py:

TheaterLocation = [
    (1, 'Naharlagun'),
]

FloorLevel = [
    (1, 'Ground Floor'),
    (2, 'Balcony'),
]

Row = [

]

Column = [

]

class Seat(models.Model):
    theater_location = models.PositiveIntegerField(choices=TheaterLocation)
    floor_level = models.PositiveIntegerField(choices=FloorLevel)
    row_id = models.PositiveIntegerField()
    column_id = models.PositiveIntegerField()

    @property
    def seat_id(self):
        return "%s : %s : %s : %s" % (self.theater_location, self.floor_level, self.row_id, self.column_id)

What I would like to do is, create a list of choices for Row and Column automatically like this:

Row = [
    (1, 'A'),
    (2, 'B'),
    ...
    ...
    (8, 'H'),
]

Column = [
    1,2,3,4,5, ... , 22
]

How can I achieve like the above?

Upvotes: 0

Views: 778

Answers (2)

arie
arie

Reputation: 18972

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

Upvotes: 1

chaos
chaos

Reputation: 490

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.

Upvotes: 0

Related Questions