ModelForm中的ManyToMany字段的自定义HTML

时间:2011-12-05 00:47:19

标签: python django django-forms django-templates

我目前正在处理一个表单,该表单显示有关我网站上特定产品的信息。每个价格由 Price 对象表示,每个 Item 都有几个与之关联的 Price 对象。我创建了一个ModelForm来显示我的 Item 中的数据。但是,当我尝试在ModelForm中显示ManyToMany字段时,我会得到一个小框,其中列出了我的所有 Price 对象。我需要为 Price 对象显示自定义HTML,以便我可以让它们与我拥有的一些JavaScript进行交互。以下是我到目前为止的代码:

class Item(models.Model):
    user        = models.ForeignKey(User)
    name        = models.CharField(max_length=200)
    description = models.CharField(max_length=1000)
    category    = models.ForeignKey(Category)
    prices      = models.ManyToManyField(Price, blank=True)
    images      = models.ManyToManyField(Image)
    runs        = models.ManyToManyField(ActivityRun, blank=True)
    date_added  = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return self.name

class ItemForm(ModelForm):
    class Meta:
        model = Item
    description = forms.CharField(widget=TinyMCE())

@login_required
def edit_item(request, item_id):
    item = get_object_or_404(Item, pk=item_id)
    if request.method == 'POST':
        form = ItemForm(request.POST, request.FILES, instance=item)
        if form.is_valid():
            return HttpResponseRedirect("/items/")
    else:
        form = ItemForm(instance=item)

    return render(request, 'edit_item.html', {'form': form})

我试图展示的模板部分:

{% for price in form.prices %}
    <span class="price_box" style="width: 200px;">
        <a href="#" class="remove_price">x</a>{{ price.name }} ${{ price.price }}
    <input type="hidden" name="price_name" value="{{ price.name }}">
    <input type="hidden" name="price_cost" value="{{ price.price }}">
    </span>
{% endfor %}

我不完全确定如何实现这一目标。 。

更具体地说,如何更改表单中多人显示的HTML?

1 个答案:

答案 0 :(得分:0)

一种方法是使用inline_modelformset来编辑价格。这可能要求您将项目模型更改为没有M2M到价格,而是将项目作为FK到价格。

这样,您可以使用Price的自定义表单,并拥有一个或多个将自动与Item相关的PriceForm实例。 formset也将具有删除功能,如果您愿意,可以通过Ajax处理。您还可以动态添加/删除表单。

希望能帮到你。

相关问题