5

I have two models, Product and Category and ManytoMany field in Product. The Category appear as key on ProductCreate View.

I need to customize the widget and field for Categories.

I checked in Django source Fields and Widgets but I don't see a reference(class) for ManyToMany.

To what type of Field and Widget ManyToMany relationship corresponds(I presume is Charfield as save or SelectField)? Where I can find the code ? (an example to customize field/widget in this case)

user3541631
  • 3,686
  • 8
  • 48
  • 115

2 Answers2

7

A model ManyToManyField is represented as a MultipleChoiceField and the default widget is SelectMultiple But, we can customise it. You can find it in below references.
[1]https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#field-types
[2]https://docs.djangoproject.com/en/dev/ref/forms/widgets/#setting-arguments-for-widgets

anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
2
from django import forms
from . import models

class ProductForm(forms.ModelForm):
    class Meta:
        model = models.Post
        fields = [<fields-for-your-product-form>]
    
    categories = forms.ModelMultipleChoiceField(
        queryset=models.Category.objects.all(),
        widget=forms.CheckboxSelectMultiple
    )

This will render checkboxes in your form but you can substitute it with your preferred widget.

I've done something similiar where I was adding tags to blog posts. I wrote a tutorial for it- goes into more detail: https://ctrlzblog.com/how-to-add-tags-to-your-blog-a-django-manytomanyfield-example/

alcampk
  • 71
  • 1
  • 4