简体   繁体   中英

MultipleChoiceField : check all if nothing is checked

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

if 'dicos' not in getcopy:
            for dic in Dico.objects.all():
                getcopy.update({'dicos': dic.id})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM