我试图通过django引导模式表单包将数据保存在带有ManyToMany字段的django中,但没有成功。我尝试覆盖save方法,但kwargs['instance']
总是返回ManyToMany字段('suppliers'
(的空dict:
{'name': 'product_1', 'all_suppliers': <QuerySet []>, 'suppliers': <QuerySet []>}
我试图实现的是为product
更新suppliers
和/或从supplier
更新products
Django完全陌生,所以请原谅糟糕的编程风格
你能帮帮我吗。谢谢
这是我的代码:
型号.py
# models.py
class Product(models.Model):
name = models.CharField(unique=True, max_length=100)
active = models.BooleanField(default=True)
def __str__(self):
return self.name
class Supplier(models.Model):
name = models.CharField(unique=True, max_length=100)
supplier_products = models.ManyToManyField(Product)
def __str__(self):
return self.name
视图.py
# views.py
class ProductUpdateView(BSModalUpdateView):
model = Product
template_name = 'product/product_update.html'
form_class = ProductForm
success_url = reverse_lazy('product_list_view')
class SupplierUpdateView(BSModalUpdateView):
model = Supplier
template_name = 'product/supplier_update.html'
form_class = ProductForm
success_url = reverse_lazy('supplier_list_view')
表单.py
# forms.py
class ProductForm(BSModalForm):
all_suppliers = forms.ModelMultipleChoiceField(queryset=Supplier.objects.all(),required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if kwargs.get('instance'):
suppliers = kwargs['instance'].supplier_set.all()
print(type(kwargs['instance']))
self.fields['suppliers'] = forms.ModelMultipleChoiceField(required=False, queryset=suppliers)
class Meta:
model = Product
fields = ['name', 'notes']
fields.append('all_suppliers')
也许您的错误是因为在向其中添加许多字段(供应商(之前需要保存产品实例。请查看此文档。我希望能帮助你
我相信它会保持这样的状态(以此为基础进行搜索(:
def save(self, commit=True):
product = super(ProductForm, self).save(commit=False)
if commit:
product.save()
suppliers = self.cleaned_data['supplier_products']
for s in suppliers:
product.suppliers.add(s)
product.save()
return product
我得到了这个,我正在使用管理屏幕,你会认为它可以处理向新工具添加新标签的情况。
ManyToManyField闯入Admin屏幕,应该';t为