我有一个模型属性和产品,声明如下:
class Attribute(models.Model):
value = models.TextField()
owner = models.ForeignKey(User)
type = models.ForeignKey(AttributeType)
image = ImageField(upload_to='attributes', null=True, blank=True)
related_attribute = models.ManyToManyField('self', blank = True, null = True)
class BaseWorkspace(models.Model):
name = models.CharField(max_length=255)
owner = models.ForeignKey(User)
attributes = models.ManyToManyField('Attribute', blank = True, null = True)
created = CreationDateTimeField()
modified = ModificationDateTimeField()
comments = models.ManyToManyField('Comment', blank = True, null = True )
sort_order = models.IntegerField(blank = True)
class Product(BaseWorkspace):
project = models.ForeignKey('Project', related_name='products')
如何使用表单集建立 mm 关系?我尝试过这样的模型表单集工厂:
AttributeFormset = modelformset_factory(Attribute, form=AttributeForm)
在通用视图中使用此功能:
def form_valid(self, form):
f = form.instance
f.sort_order = Product.default_sort_order()
f.owner = self.request.user
f.project = get_object_or_404(Project, pk=self.kwargs['pk'])
context = self.get_context_data()
attribute_form = context['attribute_form']
if attribute_form.is_valid():
self.object = form.save()
attribute_form.instance = self.object
attribute_form.save()
return HttpResponseRedirect(reverse(self.get_success_url()))
else:
return self.render_to_response(self.get_context_data(form=form))
但我无法让它工作。有任何想法吗?