问题
I have a drop down (select) form that pulls the select options form a database table. The options change almost all the time depending on certain variable.
I need to add one more option all the way to the bottom of the drop down that will always be the same. Something that will say "more options". Any ideas? Thanks!
回答1:
This is easy enough to do by overriding __init__
on the Form sub-class you're using. It should work equally well on a ModelForm as well. I'm not sure how you're populating the choices based on the question though.
class ChoiceForm(Form):
choice = ModelChoiceField(queryset=MyModel.objects.all())
def __init__(self, *args, **kw):
super(ChoiceForm, self).__init__(*args, **kw)
# Add to choices iterator
choice_field = self.fields['choice']
choice_field.choices = list(choice_field.choices) + [(0, 'More Options')]
This gives the following when rendered with <p>
tags:
<p>
<label for="id_choice">Choice:</label>
<select name="choice" id="id_choice">
<option value="" selected="selected">---------</option>
<option value="0">More Options</option>
</select>
</p>
Be warned though, this fields choices will be fixed after you create it. A normal ModelChoiceField will auto-update its choices if the results of the queryset you passed it would be changed.
回答2:
I would solve in this way: 1- render the select box as you currently do 2- create two hidden select boxes, 1 with limited choices and the other with the full list 3- when the user clicks on the "more options" button all options are flushed and the it will be repopulated with the ones from the full select box. 4- as an option you may want the user to go back to "less options", in this case you just have to flush again the options and to load from the hidden select box with limited choices.
In order to to that you just need the template to render the 2 select boxes (less opts and more opts) with style="display:none" css property and then to write the js button(s) click event (I would normally to that in jQuery) to do the switching.
Hope it helps, just ask if you need some code samples
来源:https://stackoverflow.com/questions/4843167/django-insert-a-custom-option-in-a-select-statement-that-is-auto-generated-fro