使用ModelForms保存ManyToManyFields

时间:2019-07-08 19:38:04

标签: django

我是Django的新手。我正在尝试创建Django应用。它具有端口列表和internalapp模型。我正在使用ModelForm创建Internalapp条目。但是,问题在于内部应用程序模型中的端口是ManyToManyField。当我创建internalapp的新条目时,ports字段(ManyToManyField)不会将数据保存到数据库中。下面,我提供我的modles.py,forms.py和views.py代码段。 任何帮助将不胜感激。

models.py

         class portList(models.Model):

                PROTOCOL = (("tcp","TCP"),("udp","UDP"),("icmp","ICMP"))

                appName =  models.CharField(max_length=50)
                serviceName = models.CharField(max_length=50)
                protocol = models.CharField(max_length=10, choices=PROTOCOL, default= "TCP")
                reviewDt = models.DateField(default=date.today) 
                status = models.CharField(max_length=20,null=True)

                def __str__(self):
                    return self.serviceName

            class internalapp(models.Model):
                PERIMETER_DOM = (("All","All"),("ECN","ECN"),("GIZ","GIZ"),)
                plAppConfig  = models.CharField('PaloAlto Application Config',max_length=1000, blank=False, null=True)
                comment   = models.CharField('Comments',max_length=500, blank=False, null=True)
                createdDt = models.DateField('Creation Date',default=date.today)                             # Automatically set the field to now when the object is first created. 
                ports = models.ManyToManyField(portList,blank=True)

                def __str__(self):
                    return self.servGrpNm

forms.py

            class InternalappModelForm(forms.ModelForm):
                groupInd = forms.IntegerField(label='Group Index',min_value=0)
                appGrpNm = forms.CharField(label='Application Group Name',help_text="This field consists of Perimeter Dom, Group Index and Appliction Function name" )
                servGrpNm = forms.CharField(label='Service Group Name',help_text="This field consists of Perimeter Dom, Group Index and Appliction Function name")
                comment = forms.CharField(widget=forms.Textarea(attrs={'cols': 50, 'rows': 3}),required=False)
                ports = forms.ModelMultipleChoiceField(queryset=portList.objects.all(),required=False)
                class Meta:
                    model=internalapp
                    fields = ['appGrpNm',
                              'servGrpNm',
                              'perimeter',
                              'groupInd',
                              'appGrpFunc',
                              'comment',
                              'ports']

views.py

            def new_create(request):
                if request.method == 'POST':
                    form = InternalappModelForm(request.POST)
                    if form.is_valid():
                        appObj= internalapp()
                        appObj = form.save()
                        return redirect('home')
                else:
                    form = InternalappModelForm()
                    print(request.POST)
                return render(request,'crud/created.html', {'form': form})

1 个答案:

答案 0 :(得分:1)

您需要手动保存多对多关系

if form.is_valid():
    appObj = form.save()
    appObj.ports.add(*form.cleaned_data['ports'])
    return redirect('home')