Using dynamic selection field in Django

I have choiceField to create a select box with some options. Something like that:

 forms.py class NewForm(forms.Form): title = forms.CharField(max_length=69) parent = forms.ChoiceField(choices = CHOICE) 

But I want to be able to create parameters without having a predefined tuple (which is required by choiceField ). Basically, I need to have access to request.user to populate some parameter tags according to each user, but I don't know if there is a way to use the request in form classes. Form.

An alternative would be to preinstall an instance of NewForm with:

 views.py form = NewForm(initial={'choices': my_actual_choices}) 

but I have to add a dummy CHOICE method to create a NewForm, and my_actual_choices doesn't seem to work.

I think the third way to solve this is to subclass ChoiceField and override save() , but I'm not sure how to do it.

+6
source share
1 answer

You can dynamically populate them by overriding init , basically the code will look like this:

 class NewForm(forms.Form): def __init__(self, choices, *args, **kwargs): super(NewForm, self).__init__(*args, **kwargs) self.fields["choices"] = forms.ChoiceField(choices=choices) 

NewForm(my_actual_choices) or NewForm(my_actual_choices, request.POST, request.FILES) , etc.

+7
source

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


All Articles