I needed to use a TextInput
in a CreateView
for a ManyToManyField
and I couldn't find a simple good solution. After looking through the Django source code I noticed that value_from_datadict()
is used for ManyToManyField
inputs.
In the forms.py
file you need something like:
from django.forms import ModelForm, TextInput
from .models import Product
class ManyToManyInput(TextInput):
def value_from_datadict(self, data, files, name):
value = data.get(name)
if value:
return value.split(',')
class CreateForm(ModelForm):
class Meta:
model = Product
fields = ['name','ingredients']
widgets = {
'ingredients': ManyToManyInput()
}
In the views.py
you need something like:
#...
from .forms import CreateForm
#...
class CreateView(LoginRequiredMixin, generic.edit.CreateView):
template_name = 'products/add.html'
model = Product
form_class = CreateForm
ManyToManyInput
expects a value like 2,4,6
where the numbers are the pks (ids in my case) of the model referenced by the ManyToManyField
.
This solution also works with HiddenInput
(which I ended up using).