In Django, how can I have a form where I can specify any of two sides of a m2m relation?

StackOverflow https://stackoverflow.com/questions/8276052

  •  09-03-2021
  •  | 
  •  

سؤال

I have a model similar to:

class Node(models.Model):
    output_edges = models.ManyToManyField('self', related_name='input_edges', symmetrical=False, blank=True)

I would like to create/have a form (ModelForm?) where I would be able to specify output_edges, input_edges (or even both) and they would be properly stored. By default, form for the above model works only when POST contains output_edges values. But not input_edges.

هل كانت مفيدة؟

المحلول

OK, I think I managed:

class NodeModelForm(forms.ModelForm):
    input_edges = forms.ModelMultipleChoiceField(queryset=models.Node._default_manager.all(), required=False)

    def save(self, commit=True):
        instance = super(NodeModelForm, self).save(commit=False)

        super_save_m2m = self.save_m2m
        delattr(self, 'save_m2m')

        def save_m2m():
            super_save_m2m()

            if self._meta.fields and 'input_edges' not in self._meta.fields:
                return
            if 'input_edges' in self.cleaned_data:
                setattr(instance, 'input_edges', self.cleaned_data['input_edges'])

        if commit:
            instance.save()
            save_m2m()
        else:
            self.save_m2m = save_m2m

        return instance
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top