I have the following models,
### models.py
class Foo(models.Model):
name = models.CharField(max_length=200)
class Bar(models.Model):
foo = models.ForeignKey(Foo)
baz = models.ManyToManyField(Baz, through='Between')
class Baz(models.Model):
name = models.CharField(max_length=200)
class Between(models.Model):
foo = models.ForeignKey(Foo)
bar = models.ForeignKey(Bar)
CHOICES = (
('A', 'A'),
('B', 'B'),
('C', 'C'),
)
value = models.CharField(max_length=1, choices=CHOICES)
and I have the following forms,
### forms.py
class FooForm(forms.ModelForm):
class Meta:
model = Foo
class BarForm(forms.ModelForm):
baz = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(),
queryset=Baz.objects.all())
class Meta:
model = Bar
exclude = ('foo',)
BarFormSet = inlineformset_factory(Foo, Bar, form=BarForm, can_delete=False)
Now, this works great in that I can render a single Foo and I get a number of inline forms for Bar. This renders is that the inline BarForm renders all the options of Baz as checkboxes.
What I would like is for each record of Baz to be rendered as a set of radio buttons representing the possible choices for value—along with a “N/A” choice—so that if A,B, or C is selected then the relationship to Baz is implied. But by default there doesn’t seem to be a nice way of doing this with completely re-implementing RadioSelect or implementing a completely new widget, but I would like to follow the path of least resistance.
Hopefully I am making things clear.
My solution was to create
SuperFormwhich allows subforms. The total solution is not quite generic for everyone but I did my best here to take what I was using and make it a bit more general.Here is
models.py:Here is what is in my
forms.py:Here is the
views.py:And here is the template as I render it: