django:将表单字段添加到另一个表生成的表单中
我有此表产品:
尺寸
颜色
等等
I have this table Products:
size
color
etc
和另一张桌子图片:
product_id
图片
and another table Pictures:
product_id
picture
,并且我已经从产品"表中生成了表单,但是我还需要一个用于向该产品添加图片的字段.可以在产品生成的图片表格中添加字段吗?
and I have generated form from Products table, but I also need there field for adding a picture to that product. Is it possible to add a field to the product generated form for a picture?
谢谢.
您可以使用从图片模型表单中排除产品字段.在视图中,检查两个表格是否均有效.如果两种形式均有效,则保存两种形式,但对图片形式使用commit=False
,以便您可以手动设置产品.
Exclude the product field from the picture model form. In the view, check if both forms are valid. If both forms are valid, save both forms, but use commit=False
for the picture form so that you can manually set the product.
将所有内容放在一起,您的表单和视图应如下所示:
Putting that all together, your forms and view should look something like this:
class ProductForm(forms.ModelForm):
class Meta:
model = Product
class PictureForm(forms.ModelForm):
class Meta:
model = Picture
exclude = ('product',)
def my_view(request):
if request.method == "POST":
product_form = ProductForm(prefix="product", data=request.POST)
picture_form = PictureForm(prefix="picture", data=request.POST, files=request.FILES)
if product_form.is_valid() and picture_form.is_valid():
product = product_form.save()
picture = picture_form.save(commit=False)
picture.product=product
picture.save()
return HttpResponseRedirect("/success_url/")
else:
product_form = ProductForm(prefix="product")
picture_form = PictureForm(prefix="picture")
return render(request, "my_template.html", {'product_form':product_form,
'picture_form': picture_form,
})
您的模板应如下所示:
<form>
<table>
<tbody>
{{ product_form }}
{{ picture_form }}
</tbody>
</table>
<p><input type="submit" value="Submit" /></p>
</form>