'A MultiSelectField with a select2 widget is not properly working for EDIT in Django

I have a form I am trying to understand its behaviour in Django.

The form code looks like :

class RequestForm(forms.ModelForm):
    
    TIMEPOINTS = (
            ("1M" , "1M"),
            ("2M" , "2M"),
            ("4M" , "4M"),
            ("6M" , "6M"),
            ("9M" , "9M"),
            ("1Y" , "1Y"),
            ("2Y" , "2Y"),
            ("3Y" , "3Y"),
            ("4Y" , "4Y"),
            ("5Y" , "5Y"),

    )
    timepoint = forms.MultipleChoiceField(choices=TIMEPOINTS)

    def __init__(self, *args, **kwargs):
        
        super(RequestForm, self).__init__(*args, **kwargs)
        
        self.fields['timepoint'].required = False
    
    class Meta:
        model = Request
        fields = '__all__'
        exclude = ('request_task_id', 'request_status',)
        widgets = {
            'timepoint': forms.Select(attrs={'class': 'select2 timepoint form-control'})
        }

I have a classic view

@login_required
def edit_request(request, pk):
    data_request = Request.objects.get(id=pk)
    form = RequestForm(instance=data_request)

    if request.method == 'POST':
        form = RequestForm(request.POST, instance=data_request)
        if form.is_valid():
            new_req = form.save(commit=False)
            new_req.created_by = request.user
            new_req.save()
            messages.success(request, ' Request Edited Successfully')
            return redirect("data-requests")
    else:
        form = RequestForm(instance=data_request)
    
    context = {
        'form': form,
        'data_request' : data_request,
    }
    return render(request, 'extractor/datarequest_edit.html', context)

The problem with this code and the behaviour hat I dont undertant is this :

1- The form works fine when I select many timepoints in the form, it saves as a charfield
2- When I want to edit I cannot find my options on the field
3- When I pick only one opton, it saves and displays
4- When I pick more than one option, nothing displays in the form (select2) but the database shows that the form is saved and the data is saved

I am not sure what I am missing here

Any help is more than welcome

thanks



Solution 1:[1]

I solved by problem with a better structure of my code, I switched everything into other models as a ManyToMany relationship and everything works fine now

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rad