M2m fileds select multiple on django form

Dear,
are there any tutorial to create a m2m field in front end to select many objects with a plus button like in admin mode?

I would like create a multiple selection chech box to select many objects to add to current object in m2m field

Thanks
Regards
MD

Hi Maurilio,
You can use MultipleChoiceField in your model form field . Its the field of model form class of corrosponding field of model class . In Front end you will see as multiselect checkbox .
let say my models are -

class Country(models.Model):
name = models.CharField(max_length=30)
status = models.IntegerField(default=1)
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.name


class Hobby(models.Model):
name = models.CharField(max_length=30)
status = models.IntegerField(default=1)
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return self.name


class PersonDetail(models.Model):
GENDER = (
    ('M','Male'),
    ('F','Female')
)
user = models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE)
name = models.CharField(max_length=20)
gender = models.CharField(max_length=10,choices=GENDER)
dob = models.DateField()
mobile = models.IntegerField()
email = models.EmailField()
aadhaar = models.IntegerField()
country = models.ForeignKey(Country,on_delete=models.CASCADE)
address = models.TextField()
hobby = models.ManyToManyField(Hobby,null=True)
status = models.IntegerField(default=1)
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return '{} - {}'.format(self.name,self.email)

and then my ModelForm class -

class PersonDetailForm(forms.ModelForm):

# def __init__(self,*args,**kwargs):
#     super(PersonDetailForm,self).__init__(*args,**kwargs)
#     self.user = kwargs.pop('user',None)
hobby = forms.ModelMultipleChoiceField(queryset=Hobby.objects.filter(status=1),
                                               widget=forms.CheckboxSelectMultiple, required=False)
class Meta:
    model = PersonDetail
    fields = ('name','gender','dob','mobile','email','aadhaar','country','address','hobby')

    widgets = {
        'dob': forms.DateInput(attrs={'type':'date'}),
        'address':forms.Textarea(attrs={'cols':10,'rows':3})
    }
    labels = {
        'name':'Display Name'
    }

Here is the UI -

Thanks,
Is it possible to insert all those checkboxes
In a filterable list view?

Thanks
Regards
MD

Hi Maurilio,
I’m not getting . Whats your requirements ?

Dear, I’ve made a little app to control maintenance in my factory, I created model for order and part, now, in order detail view I need link m2m field of part. When I create a maintenance order, I need select one or more spare parts from its detail view. Spare parts can be 200 o 300 and with chechboxes is not good for more than 10 o 20 elements.
Thanks
Regards
MD

Then in that case i will suggesst you to categories your Spare Parts, based on category you select , spare part checkbox will be filtered and number will be reduced to 10-20 .

Good, I’ll try to do in this manner
thanks
regards

Here my models

class Part(models.Model):
objects = models.Manager()
now = datetime.datetime.now
id = models.AutoField(primary_key=True)
partid = models.UUIDField(default=uuid.uuid4)
vendorid = models.ManyToManyField(
Vendor, blank=True, null=True)
codiceproduttore = models.CharField(max_length=50, default=‘XXXXXX’)
codice = models.CharField(max_length=50, default=‘XXXXXX’)
active = models.BooleanField(default=True)
category = models.CharField(max_length=60, choices=PART_CATEGORY, default=‘RICAMBIO’, editable=True)
description = models.CharField(max_length=250)
level = models.IntegerField(default=1, blank=True, null=True)
name = models.CharField(max_length=50)
note = models.CharField(max_length=250, blank=True, null=True)
parentid = models.CharField(max_length=50, blank=True, null=True)
price = models.FloatField(default=0.0)
value = models.FloatField(default=0.0)
value_date = models.DateTimeField(default=now, editable=False)
code = models.CharField(max_length=50, blank=True, null=True)
qty = models.FloatField(default=1.0)
uom = models.CharField(max_length=60, choices=UM, default=‘pezzi’, editable=True)
reordertype = models.CharField(max_length=60, choices=REORDER_TYPE, default=‘MANUALE’, editable=True)
criticality = models.IntegerField(default=1, blank=True, null=True)
fastlink = models.CharField(max_length=50, blank=True, null=True)
lt = models.IntegerField(default=744, blank=True, null=True)
flevel = models.FloatField(default=0.9, blank=True, null=True)
flevelmin = models.FloatField(default=0.5, blank=True, null=True)
ir = models.FloatField(default=1.0, blank=True, null=True)
mtbf = models.BigIntegerField(default=40000, blank=True, null=True)
mttr = models.BigIntegerField(default=744, blank=True, null=True)
mdt = models.BigIntegerField(default=24, blank=True, null=True)
avail = models.FloatField(default=1.0, blank=True, null=True)
rel = models.FloatField(default=1.0, blank=True, null=True)
qual = models.FloatField(default=1.0, blank=True, null=True)
stars = models.FloatField(default=100.0, blank=True, null=True)
weib = models.FloatField(default=1.0, blank=True, null=True)
eta = models.FloatField(default=1.0, blank=True, null=True)
beta = models.FloatField(default=1.0, blank=True, null=True)
rt = models.FloatField(default=0.000025, blank=True, null=True)
work_bit = models.BooleanField(default=True, blank=True, null=True)
work = models.IntegerField(default=1, blank=True, null=True)
maintenance_bit = models.BooleanField(default=True, blank=True, null=True)
maintenance = models.IntegerField(default=0, blank=True, null=True)
mttf = models.IntegerField(default=744, blank=True, null=True)
mttf_bit = models.BooleanField(default=True, blank=True, null=True) # allo scadere di mttf viene messo a true
image = models.ImageField(upload_to=‘uploads/’, blank=True, null=True)
rwop = models.DateTimeField(default=now, editable=False)
box = models.CharField(max_length=50)
x = models.IntegerField(default=1, blank=True, null=True)
y = models.IntegerField(default=1, blank=True, null=True)
z = models.IntegerField(default=1, blank=True, null=True)
comment = models.CharField(max_length=250, default=‘commento’, blank=True, null=True)
priority = models.CharField(max_length=60, choices=PRIORITY, default=‘NORMAL’, editable=True)
warranty = models.CharField(max_length=50, default=‘garanzia’, blank=True, null=True)
createdby = models.CharField(max_length=50, default=‘creatoda’, blank=True, null=True)
workshop = models.CharField(max_length=60, choices=WORKSHOP, default=‘INTMAINT’, editable=True)
documents = models.CharField(max_length=50, default=‘documenti’, blank=True, null=True)
severity = models.BigIntegerField(default=10, blank=True, null=True)
occurrence = models.BigIntegerField(default=10, blank=True, null=True)
detection = models.BigIntegerField(default=10, blank=True, null=True)
RPN = models.BigIntegerField(default=10, blank=True, null=True)
score = models.BigIntegerField(default=10, blank=True, null=True)
default = models.BooleanField(default=False, blank=True, null=True)
email1 = models.EmailField(default=‘mail1@mail.com’, blank=True, null=True)
email2 = models.EmailField(default=‘mail2@mail.com’, blank=True, null=True)
email3 = models.EmailField(default=‘mail3@mail.com’, blank=True, null=True)

class Asset(models.Model):
objects = models.Manager()
now = datetime.datetime.now
id = models.AutoField(primary_key=True)
assetid = models.UUIDField(default=uuid.uuid4)
assetcode = models.CharField(max_length=50, default=‘100’, blank=True, null=True)
active = models.BooleanField(default=True)
category = models.ManyToManyField(
Category)
description = models.CharField(max_length=250, default=‘Production System’)
level = models.IntegerField(default=2, blank=True, null=True)
name = models.CharField(max_length=250, default=‘System Name’, blank=True, null=True)
note = models.CharField(max_length=250, default=‘System Note’, blank=True, null=True)
parentid = models.CharField(max_length=50, default=0, blank=True, null=True)
start = models.DateTimeField(default=now, editable=True, blank=True, null=True)
mtbf = models.BigIntegerField(default=40000, blank=True, null=True)
mttr = models.BigIntegerField(default=48, blank=True, null=True)
mdt = models.BigIntegerField(default=2, blank=True, null=True)
avail = models.FloatField(default=0.9, blank=True, null=True)
rel = models.FloatField(default=0.9, blank=True, null=True)
qual = models.FloatField(default=0.9, blank=True, null=True)
oee = models.FloatField(default=0.729, blank=True, null=True)
weib = models.FloatField(default=1.0, blank=True, null=True)
eta = models.FloatField(default=1.0, blank=True, null=True)
beta = models.FloatField(default=1.0, blank=True, null=True)
rt = models.FloatField(default=0.000025, blank=True, null=True)
work_bit = models.BooleanField(default=True, blank=True, null=True)
work = models.IntegerField(default=1, blank=True, null=True)
maintenance_bit = models.BooleanField(default=True, blank=True, null=True)
maintenance = models.IntegerField(default=1, blank=True, null=True)
setup = models.IntegerField(default=1, blank=True, null=True)
setup_bit = models.BooleanField(default=True, blank=True, null=True)
image = models.ImageField(upload_to=‘uploads/’, default=‘uploads/none/no-img.png’)
rwop = models.DateTimeField(default=now, editable=False)
createdAt = models.DateTimeField(“Created At”, auto_now_add=True)
part = models.ForeignKey(Part, on_delete=models.CASCADE, blank=True, null=True)
email1 = models.EmailField(default=‘mail1@mail.com’, blank=True, null=True)
email2 = models.EmailField(default=‘mail2@mail.com’, blank=True, null=True)
email3 = models.EmailField(default=‘mail3@mail.com’, blank=True, null=True)

class Order(models.Model):
objects = models.Manager()
now = datetime.datetime.now
id = models.AutoField(primary_key=True)
orderid = models.UUIDField(default=uuid.uuid4)
asset = models.ForeignKey(
Asset, on_delete=models.DO_NOTHING, default=None, null=False)
part = models.ManyToManyField(
Part, blank=True, null=True)
task = models.ManyToManyField(
Task, blank=True, null=True)
name = models.CharField(max_length=50, default=‘insert order name’)
category = models.ManyToManyField(
Category, blank=True, null=True, max_length=50, default=‘categoria’)
type = models.CharField(max_length=60, choices=ORDER_TYPE,
default=‘MAINT’, editable=True)
state = models.CharField(max_length=60, choices=ORDER_STATE,
default=‘ACTIVE’, editable=True) # models.foreignkey(user, on_delete=models.cascade)
description = models.CharField(max_length=250, default=‘insert order description’)
workprocedure = models.ManyToManyField(
WorkProcedure, blank=True, null=True)
jobdescription = models.ManyToManyField(
JobDescription, blank=True, null=True)
createdate = models.DateTimeField(default=now)
hse = models.CharField(max_length=50, default=‘hse description’)
planneddate = models.DateTimeField(default=now)
executiondate = models.DateTimeField(default=now)
comment = models.CharField(max_length=250, default=‘commento’)
expectedduration = models.FloatField(default=1.0)
realduration = models.FloatField(default=1.0)
numberintoperators = models.IntegerField(default=10)
numberextoperators = models.IntegerField(default=10)
priority = models.CharField(max_length=60, choices=PRIORITY, default=‘NORMAL’, editable=True)
warranty = models.CharField(max_length=50, default=‘garanzia’)
createdby = models.CharField(max_length=50, default=‘creatoda’)
workshop = models.CharField(max_length=60, choices=WORKSHOP, default=‘INTMAINT’, editable=True)
documents = models.CharField(max_length=50, default=‘documenti’)
severity = models.BigIntegerField(default=10)
occurrence = models.BigIntegerField(default=10)
detection = models.BigIntegerField(default=10)
RPN = models.BigIntegerField(default=10)
score = models.BigIntegerField(default=10)
default = models.BooleanField(default=False)
mdt = models.BigIntegerField(default=24)
avail = models.FloatField(default=1.0)
materialcost = models.FloatField(default=0.0)
manpowercost = models.FloatField(default=0.0)
totalcost = models.FloatField(default=0.0)
capex = models.FloatField(default=0.0)
opex = models.FloatField(default=0.0)
bdgt = models.CharField(max_length=50, default=‘Bdgt2022’)
image = models.ImageField(upload_to=‘uploads/’, default=‘uploads/none/no-img.png’)
email1 = models.EmailField(default=‘mail1@mail.com’)
email2 = models.EmailField(default=‘mail2@mail.com’)
email3 = models.EmailField(default=‘mail3@mail.com’)

def __str__(self):
    return self.name

def get_absolute_url(self):
    return reverse('order_create', kwargs={"pk": self.pk})