Skip to content

Instantly share code, notes, and snippets.

@stefanocoding
Last active May 20, 2021 11:02
Show Gist options
  • Save stefanocoding/4563866cef0ec197d8b1ccb183d1163d to your computer and use it in GitHub Desktop.
Save stefanocoding/4563866cef0ec197d8b1ccb183d1163d to your computer and use it in GitHub Desktop.
Using a TextInput for a ManyToManyField on Django 3. Compatible with CreateView.

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment