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.
Django forms ChoiceField with dynamic values... Published at Dec. 5, 2010 | Tagged with: Python, Django, django-forms, dynamic values, ChoiceField
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.
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 ?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With