我有两个名为product和productimage的模型。我将有多个
产品图片。所以在这个应用程序中,我想创建多个
我希望在一个
中创建多个图像的产品和每个产品使用modelformset_factory和inlineformset_factory表单。我试过了,但是
没有成功。我怎样才能做到这一点。
这里的产品是一个modelformset,而productimage是一个inlineformset
models.py :
class Product(models.Model):
title = models.CharField(max_length=128)
description = models.TextField()
image = models.ImageField(upload_to="images/")
def __unicode__(self):
return self.title
class ProductImage(models.Model):
product = models.ForeignKey(Product, related_name="%(app_label)s_%(class)s")
title = models.CharField(max_length=128)
image = models.ImageField(upload_to="images/")
def __unicode__(self):
return self.title
forms.py
Product_modelformset = modelformset_factory(Product, form=ProductForm, extra=0, min_num=1)
Productimage_inlineformset = inlineformset_factory(Product, ProductImage, form=ProductImageForm, extra=0,
min_num=1, max_num=5, can_delete=True)
views.py
def create_product(request):
template = "frontend/create_product.html"
context = {}
product_formset = Product_modelformset(queryset=Product.objects.none(), prefix="product_formset")
productimage_formset = Productimage_inlineformset(prefix="productimage_formset")
if request.method == 'POST':
pass
........
.........
context["product_formset"] = product_formset
context["productimage_formset"] = productimage_formset
return render(request, template, context)
create_product.html
{% for form in product_formset.forms %}
<div class="form_items">
<p class="lead">Product ITems</p>
{{ form.as_p }}
</div>
{% for form in productimage_formset.forms %}
<div class="image_items">
<p class="lead">image items</p>
{{ form.as_p }}
</div>
{% endfor %}
{% endfor %}
<script>
$(document).ready(function() {
$('div.form_items').formset({
prefix: "{{ product_formset.prefix }}"
});
$('div.image_items').formset({
prefix: "{{ productimage_formset.prefix }}"
});
});
</script>