[Fixed]-Can't save ManyToMany using MultipleChoiceField

1👍

Well, the basic solution still stays the same:

queryset=Employee.objects.filter(employee_id__in=['some_id', 'other_id'])

The key point is that you should use a ModelMultipleChoiceField.

If you want to display the names rather than the IDs, there are a couple of ways to do that, e.g. a get_name method on the model and a custom ModelMultipleChoiceField, as described here: https://stackoverflow.com/a/3167840/1180983

So that would look roughly like this:

EMPLOYEE_NAMES = {
    '123': 'Adam',
    '321': 'John',
}

class Employee(models.Model):
    employee_id = models.CharField(max_length=20, unique=True)

    def get_name(self):
        return EMPLOYEE_NAMES.get(self.employee_id, 'unknown')

class EmployeeMultipleChoiceField(ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.get_name()

class TaskCreateForm(forms.ModelForm)
    employees = EmployeeMultipleChoiceField(
        queryset=Employee.objects.filter(employee_id__in=['123', '321'])
    )

0👍

Your ModelForm does not know what to do with the employee field on save(), because you do not tell it anywhere, and that field is not connected to any model. Use a ModelMultipleChoiceField instead.

If you need to restrict the choices the ModelMultipleChoiceField allows, use the queryset argument:

employees = forms.ModelMultipleChoiceField(
    queryset=Employee.objects.filter(name__in=['Alice', 'Bob'])
)

Also, think about where to use plural and where to use singular names, so you do not confuse yourself (employees instead of employee above).

Leave a comment