How to programmatically set django select box?

I have a model with a select box and I want to set it while saving the form in django.

I want users to be able to generate additional model updates, and one model I want to update has a selection box. I know the value that I want this selection field to be, but when I create a new model object, how to set the selection field in the code?

For instance -

Let's say I want to create a new Auto object, and I conclude if the car is one of the options Luxury, Economy or Standard.

I want to set the value of this selection field in code before saving the model object ...

Any clues?

Thanks in advance.

+3
source share
1 answer

: http://docs.djangoproject.com/en/dev/ref/models/fields/#choices

. , :

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() , , .

+3

Source: https://habr.com/ru/post/1789300/


All Articles