0

I have a many to many field linked with my model1. Now, I created a form for this model1 and added this many to many field as a form field and used FilteredSelectMultiple widget to edit this. Now, the problem is the related many to many field has a soft delete option, which I am tracking with active field in the model2. So, now in the form all the objects are displayed even if they are deleted, is there any way I can show the objects which have active as true in this form field.

My model form looks as follows:

 class Editform(form.ModelForm):
    class Media:
       css = .. 
       js = ..
    class Meta:
        Model = model1
        fields = [ "x", "y", "ManytoManyfield"]
        widgets = {
            'ManytoManyfield': FilteredSelectMultiple("Displaay name", False)
                   }

2 Answers2

0

This answer is close to what you want. I think this may work.

You create an extra field in your ModelForm, populating it with a query.

class Editform(form.ModelForm):
    many_to_many_field_active = forms.ChoiceField(choices=[(m2m.id, m2m.name) for m2m in Model2.objects.filter(active=True)])

    class Meta:
        #...
        widgets = {
        'many_to_many_field_active': Select(attrs={'class': 'select'}),
schrodingerscatcuriosity
  • 1,780
  • 1
  • 16
  • 31
  • This shows only a single choice select field in form, I wanted to have filtered multiple select( like in django admin). – Tarun Golthi Nov 03 '17 at 13:52
0

I solved this using the multiplechoicefield in my model form as follows.

 def __init__(self, *args, **kwargs):
   many_to_m_initial = kwargs['instance'].model2.all()
   choices = [(m2m.id, m2m.name) for m2m in Model2.objects.filter(active=True)]
   self.fields['my_field'] = forms.MultipleChoiceField(choices = choices, widget=FilteredSelectMultiple("verbose name", is_stacked=False, choices=choices))
   self.initial['my_field'] = [ m2m.pk fpr m2m in many_to_m_initial ]