Reputation: 23
What I want to do seems simple : I have a MultipleChoiceField in a django form which proposes the id and pseudo of all books in a model named Dico :
class FiltreMonoForm(forms.Form):
dico_choices = []
for dic in Dico.objects.all().order_by('pseudo'):
dico_choices.append((dic.id, dic.pseudo))
dico_choices=tuple(dico_choices)
dicos = forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=dico_choices, initial=[c[0] for c in dico_choices], label="Diccionaris sorsas")
I get this form back in a view :
def monollist(request):
if request.GET:
getcopy = request.GET.copy()
form = FiltreMonoForm(getcopy)
dicos = form.cleaned_data['dicos']
else:
form = FiltreMonoForm()
I would like to have all the books checked if the user have checked none of them. Something like :
if request.GET:
getcopy = request.GET.copy()
form = FiltreMonoForm(getcopy)
dicos = form.cleaned_data['dicos']
for dic in Dico.objects.all().order_by('pseudo'):
dico_choices.append((dic.id, dic.pseudo))
dico_choices=tuple(dico_choices)
if len(dicos)==0:
form['dicos']=dico_choices
But I can't find how to change the value of the MultipleChoicesField. I tried with
form.data['dicos']=dico_choices
but it seems that I can only give one value to form.data['dicos'], it won't accept lists nor tuples.
I tried to override the __init__ method in my form in adding
self.data.update(dicos=dico_choices)
but I have the same issue, it works only if dico_choices is a single value.
Do you have any idea how to override my MultipleChoiceField with multiple values ?
Thanks
Upvotes: 0
Views: 156
Reputation: 23
if 'dicos' not in getcopy:
for dic in Dico.objects.all():
getcopy.update({'dicos': dic.id})
Upvotes: 0