djangoformslistdjango-querysetmultiplechoicefield

Set initial values on ModelMultipleChoiceField CheckboxSelectMultiple widget using list


I have a ModelMultipleChoiceField in a form which is generated with a queryset.

class NewEvaluationPriorityForm(forms.Form):

priority_field = forms.ModelMultipleChoiceField(
    queryset=None,
    widget=forms.CheckboxSelectMultiple,
    required=False
)

def __init__(self, user_type, qi_list, hgiours_list, is_hgiours_evaluation, school, *args, **kwargs):
    super(NewEvaluationPriorityForm, self).__init__(*args, **kwargs)

    if is_hgiours_evaluation is True:
        priorities = Priority.objects.get_new_hgiours_evaluation_priorities(
            hgiours_list,
            school
        )
    else:
        priorities = Priority.objects.get_new_evaluation_priorities(
            qi_list,
            user_type,
            school
        )

    self.fields['priority_field'].queryset = priorities
    self.fields['priority_field'].label = ''

What I want to do is to set the initial values of the different checkboxes in the field using a list. I have tried the following (where I know there are 5 objects in the queryset):

self.fields['priority_field'].initial = [True, False, True, False, True]

But that doesn't work.

What is it that I need to do?


Solution

  • So the solution I was looking for is that you need to provide a list of queryset keys which are to be set to True.

    So for example

    self.fields['priority_field'].initial = ['1024', '1025']
    

    where 1024 and 1025 are the pks of the queryset objects that should be checked as True

    For context, I was trying to temporarily save any checked items from my form in a request.session key if the user selected a different page, and then restore the checked items when the user returned to the form.

    The solution:

    1. Store the list of keys in a session variable when the user leaves the page using request.POST.getlist():

      request.session['selected_priorities_keys'] = request.POST.getlist('priority_field')
      
    2. Test if the session key exists when the page is reloaded

      if 'selected_priorities_keys' in request.session:
          checked_key_list = request.session['selected_priorities_keys']
      else:
          checked_key_list = []
      
    3. Pass this list to the form init and use it to initialise the ModelMultipleChoiceField field.

      self.initial['priority_field'] = checked_key_list