Django ManytoMany widget to CheckboxSelectMultiple and chained querysets
It happened that I needed a ManytoMany field to be displayed as a CheckboxSelectMultiple no problem with that. The trick part is that there are default fields to be displayed and a user should be able to add a new option and this option should be displayed on the form.
Here is what I did:
models.py
class Feature(models.Model):
name = models.CharField( _("Feature Name"), max_length=40)
default = models.BooleanField(_("Is Global Feature"), default = False)
class SomeModel(models.Model):
features = models.ManyToManyField(Feature, related_name='features')
forms.py
class FeatureForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
somemodel = kwargs['somemodel']
kwargs.pop('somemodel')
super(SpaFeatureForm, self).__init__(*args, **kwargs)
default_features = Feature.objects.filter(default=True)
开发者_开发问答 custom_features = somemodel.features.filter(default=False)
q_set = QuerySetChain(default_features, custom_features)
self.fields['features'].widget = forms.CheckboxSelectMultiple()
self.fields['features'].queryset = q_set
class Meta:
model = m.Spa
fields = ('features',)
I'll still implement the second part which will be a feature form and some sort of js to populate the Checkbox Multiselect field choices.
I modified @akaihola answer ow how to chain querysets changing def _all to def all. And it worked fine.
The question now is: Is that the best solution?
精彩评论