【问题标题】:Django Saving selected values of ManytoMany FieldDjango保存多对多字段的选定值
【发布时间】:2019-08-05 08:05:52
【问题描述】:

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

【问题讨论】:

  • 你是什么意思,“除了选中的所有字段都被保存了”?
  • 你能更清楚地解释你的问题吗?我仍然无法理解您想要实现的目标

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-10-02
    • 2014-02-26
    • 1970-01-01
    • 2018-09-30
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2021-11-16
    相关资源
    最近更新 更多