0

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?

Aamu
  • 3,431
  • 7
  • 39
  • 61

2 Answers2

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
  • 18,737
  • 5
  • 70
  • 76
  • How can I use your above code with mine? Do I use SeatForm for the `choices`? Like `row_d = models.PositiveIntegerField(choices=SeatForm)` – Aamu Feb 26 '17 at 13:46
  • No, you don't use a form as a value for choices. There is really comprehensive info about forms in the documentation: https://docs.djangoproject.com/en/1.10/topics/forms/ Assuming you are currently using the admin to enter your data, you could edit the relevant form like this: http://stackoverflow.com/a/4466958/630877 – arie Feb 26 '17 at 13:58
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
  • 480
  • 3
  • 8