Search code examples
djangodjango-widget

django one widget for two m2m fields


I have two manytomany fields for my model ModelFrom, that both go to the same Model, call it ModelTo.

ModelFrom(models.Model):
    field_one = ManyToManyField(ModelTo)
    checked = ManyToManyField(ModelTo)

checked is a subset of field one. I have properly validated this in model clean() and adminform clean() methods, and updated model::save() to call self.full_clean().

Ideally, I would have one widget, much like the django.forms.SelectMultiple, but with a checkbox inside each <option>.

what it currently looks like, I have one of these widgets for each field: current look:

I want to combine them and have a checkbox or something, here is my unicode representation of what it would look like

{ [ blah: 2 ☐] , [blah: 1 ☑] }

Value in the list -> field one is set. Checked box -> checked is set as it is a subset of field_one.

I have seen jQuery UI MultiSelect Widget but there doesn't seem to be a way to be able to select an option, but not check the box.


Solution

  • I couldn't directly answer my own question, but like most questions, if the answer is not possible then there may be an underlying problem.

    Instead of having two many2many fields, I should just have one, setting the through property, for an intermediate field. Like so:

    class IntermediateField(models.Model):
         checked = BooleanField()
         from = ForeignKey(ModelFrom)
         to = ForeignKey(ModelTo)  
    
    ModelFrom(models.Model):
        field_one = ManyToManyField(ModelTo, through=IntermediateField)
    

    Then, we can just use an inline for IntermediateField in ModelFrom admin, easily checking the boxes etc