Django保存ManytoMany字段的选定值

时间:2019-03-14 12:16:31

标签: django django-models django-forms django-views manytomanyfield

在这里,我试图将选定的字段保存在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

#form

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>

1 个答案:

答案 0 :(得分:0)

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

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