django:将表单字段添加到另一个表生成的表单中 [英] django: add form field to generated form from another table

查看:100
本文介绍了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>

这篇关于django:将表单字段添加到另一个表生成的表单中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆