Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using dynamic Choice Field in Django

I have a choiceField in order to create a select field with some options. Something like this:

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 the options without having a predefined tuple (which is required by ChoiceField). Basically, I need to have access to request.user to fill some options tags according to each user, but I don't know if there is any way to use request in classes of forms.Form.

An alternative would be to prepopulate the instance of NewForm via:

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

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

I think a third way to solve this is to create a subclass of ChoiceField and redefined save() but I'm not sure how to go about doing this.

like image 433
Robert Smith Avatar asked Jul 21 '12 00:07

Robert Smith


People also ask

Does Django form choicefield with dynamic values?

Django forms ChoiceField with dynamic values... Published at Dec. 5, 2010 | Tagged with: Python, Django, django-forms, dynamic values, ChoiceField

What are dynamic fields in Django?

Such fields are derived from other fields of the same entity (model) and they might change over time (age, for example). We can create dynamic fields in django in more than one way.

How to initiate a form in Django?

Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html. Finally, a URL to map to this view in urls.py Thus, an geeks_field ChoiceField is created by replacing “_” with ” “. It is a field to input choices of strings. How to use ChoiceField ?

How to set the value of my choice field to dynamic?

ChoiceField(choices=MY_CHOICES) So if you want the values to be dynamic(or dependent of some logic) you can simply modify your code to something like this: defget_my_choices():# you place some logic herereturnchoices_listclassMyForm(forms. Form):my_choice_field=forms. ChoiceField(choices=get_my_choices()) and here you will fail(not absolutely).


1 Answers

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

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.

like image 138
surfeurX Avatar answered Sep 21 '22 09:09

surfeurX