Django ManytoManyField and widgets

Viewed 11778

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)

2 Answers
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/

Related