python - Django - 使用 Formsets 在不通过表的情况下在 2 个模型之间建立多对多关系

标签 python django forms

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

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

如何使用表单集建立 m-m 关系?我试过这样的模型表单集工厂:

AttributeFormset = modelformset_factory(Attribute, form=AttributeForm)

在通用 View 中使用此功能:

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

但我无法让它工作。有什么想法吗?

最佳答案

尝试这样的事情:

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

    ...

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

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

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

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

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

关于python - Django - 使用 Formsets 在不通过表的情况下在 2 个模型之间建立多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13775261/

相关文章:

django - 当达到并发值时,Celery inspect 显示 worker 离线

python - 文件没有关闭

Python:即使不满足条件,如果仍在运行

python - celery + RabbitMQ + "A socket error ocurred"

javascript - document.getElementById 的日期时间不起作用

Javascript 增加输入结果并包含逗号

html - 如果我将元素放在表单之外,如何将元素放在同一行

Python Split Dict[String, List[String]] 到 List[Dict[String, String]] 并保留每个键

python - python 2.7中列表索引超出范围

django - 如何将 MultipleChoiceField 保存到数据库