Django 保存 ManytoMany 字段的选定值

Django Saving selected values of ManytoMany Field

这里我试图在 manytomany 字段中保存选定的字段。 当我尝试保存选定字段时,除选定字段外的所有字段也将被保存。我怎样才能只保存选定的字段。 这是我的模型..

#model 
class Products(models.Model):
    name = models.CharField(max_length=128)
    product_code = models.CharField(max_length=128)
    cmp_id = models.ManyToManyField(Components, blank=True)
    bay_id = models.ManyToManyField(ScanningBay, blank=True)
    def __str__(self):
        return self.name

#表格

class ProductForm(forms.ModelForm):
    name =  forms.CharField(max_length=15,widget=forms.TextInput(attrs={'class':'form-control','placeholder': 'Product Name','size': '40'}))
    product_code = forms.CharField(max_length=15, widget=forms.TextInput(
        attrs={'class': 'form-control', 'placeholder': 'Product Code', 'size': '40'}))
    bay = forms.ModelMultipleChoiceField(queryset=ScanningBay.objects.all())
    component = forms.ModelMultipleChoiceField(queryset=Components.objects.all())
​
    class Meta:
        model = Products
        fields = ('name', 'product_code','bay','component')"

#views

def products(request):
    if request.method == 'POST':
        p_form = ProductForm(request.POST or None)
        new = p_form.save(commit=False)
        new.save()
        z = p_form.save_m2m()
        print (z)
        return HttpResponse("success")
    else:
        pdct_form = ProductForm()
        return render(request, 'app/products.html', {'pdct':pdct_form})

这是呈现的模板

<form id="test" class="impexform" action="{%url 'products'%}" method="POST">
                     {% csrf_token %}>
                    {{pdct}}
<button type="submit" class="btn btn-sm btn-danger mt-3"
                            style="background:#ed2526; border-radius: 30px; width: 8rem;">Add Product</button>
</form>

您表单中的字段与模型中的字段不匹配:

class ProductForm(forms.ModelForm):
    ...
    cmp_id = forms.ModelMultipleChoiceField(queryset=Components.objects.all())
​
    class Meta:
        model = Products
        fields = ('name', 'product_code','bay','cmp_id')"