4

我有一个模型属性和产品,声明如下:

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))

但我无法让它工作。有任何想法吗?

4

2 回答 2

0

尝试这样的事情:

from django.forms.models import modelformset_factory
def my_view_function(request) :

    # not sure where the product whose formset we are working on comes from
    product = <whatever>

    AttributeFormSet = modelformset_factory(Attribute)

    if request.method == "POST" :
        # POST bound formset
        formset = AttributeFormSet(request.POST, queryset=Attribute.objects.filter(product=product))
        # If the entire formset is valid
        if formset.is_valid() :
            for form in formset:
                # Save each form in the set
                b = form.save()
        else : 
            #There was an error (add a message using the messages framework?)
            pass
    else :
        # initial formset w/o post
        formset = AttributeFormSet(queryset=Attribute.objects.filter(product=product))

    ...

很难给您更具体的答案,我认为如果您使用基于类的视图,我们将需要整个视图函数或视图类。

在您的模板中,像这样简单的事情(来自文档)应该可以做到。

<form method="post" action="">
    {{ formset.management_form }}
    <table>
        {% for form in formset %}
        {{ form }}
        {% endfor %}
    </table>
</form>

如果您需要能够在运行时使用 javascript 将表单添加到表单集,请查看:http ://code.google.com/p/django-dynamic-formset/ 。我从未使用过它,但至少它看起来像是朝着正确方向迈出的一步。

编辑

首先从表单集中排除产品

AttributeFormSet = modelformset_factory(Attribute, exclude=('product',))

然后将表单处理块更改为在保存时不提交,并手动附加产品。

        if formset.is_valid() :
            for form in formset:
                # get this form's instance
                b = form.save(commit=False)
                # attach product
                b.product = product
                # save the instance
                b.save()
于 2012-12-14T16:09:00.900 回答
0

通过使用f = form.instance您可以访问原始实例。如果attribute_form 是有效的,你调用save 方法form,而不是f。您所做的所有更改f都将丢失。

看看save-objects-in-the-formset如何在保存表单集的实例之前更新它们。

于 2012-12-17T09:19:23.727 回答