Y
Y
YuriyCherniy2020-01-24 12:29:33
Django
YuriyCherniy, 2020-01-24 12:29:33

How to make the choices argument of a TypedChoiceField in a form dynamically changeable?

I'm trying to make an application - the editor of the main page of the showcase site. The main page should display a maximum of 9 products. But I want the user to display a selection with position numbers no greater than the number of the next available cell. Let's say the user has already added 3 products, which means that a maximum of 4 positions should be displayed for selection, three positions for replacement and the fourth for a new product.

class ItemOnMainPageForm(forms.Form):
    item_on_main_page = forms.ModelChoiceField(
        queryset=Item.objects.all(),
        label='Выберете товар'
    )
    position = forms.TypedChoiceField(
        choices=[
            (1, 1), (2, 2), (3, 3),
            (4, 4), (5, 5), (6, 6),
            (7, 7), (8, 8), (9, 9)
        ],
        coerce=int,
        label='Позиция на главной'
    )

The current implementation allows you to display all 9 cells at once for selection. What approach can be taken to change this behavior and force the field positionto be dynamic and match the state of the system? I suspect some workaround needs to be used since the class is read once when the server starts, but which one?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2020-01-24
@YuriyCherniy

in __init__
self.fields['position'].choices =

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question