提交多对多关系中的选定项目

时间:2018-12-31 09:44:54

标签: django django-forms django-templates

我创建了一个节点并计划了具有manyTomany关系的动作模型:

class Node(models.Model):
    name = models.CharField(default='node', max_length=32)
    nb_solenoid = models.DecimalField(max_digits=19, decimal_places=10, null=True, blank=True)
    connexion = models.CharField(max_length=255)

class ScheduledAction(models.Model):
    date = models.DateTimeField(default=datetime.now, blank=True)
    firm = models.ForeignKey('firme.Firme', on_delete=models.CASCADE, null=True, blank=True)
    node_ids = models.ManyToManyField(Node) 

在forms.py中:

class ScheduledActionForm(forms.ModelForm):
    date = forms.DateTimeField()
    firm = forms.ModelChoiceField(queryset=Firme.objects.all())
    node_ids = forms.ModelMultipleChoiceField(queryset=Node.objects.filter(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = ScheduledAction
        fields = [
            'date',
            'firm',
            'node_ids'
        ]

在views.py中:

def planification_view(request):
    scheduledAction = ScheduledActionForm(request.POST or None)
    nodes = Node.objects.all()
    if scheduledAction.is_valid():
        scheduledAction.save()
        print('formulaire enregistre')
        scheduledAction = ScheduledActionForm()
    context = {
        'form': scheduledAction,
        'nodes': nodes
    }
    return render(request, "node/planification.html", context)

该视图工作正常,但我检查的节点数始终将所有节点保存在“多对多”字段中。如何使其仅提交选定的字段?

0 个答案:

没有答案