Django使用父对象在创建视图中创建许多子对象

时间:2018-06-09 08:54:24

标签: python django-models django-forms

我有两个与外键相关的模型。我正在尝试将逻辑添加到创建视图中的表单字段,其中用户填写数字n并在数据库中生成n个项目。

Model.py

from PIL import Image

PNG_FILE = 'E:\path_to_file\15868799_1.png'
PDF_FILE = 'E:\path_to_file\15868799.pdf'

rgba = Image.open(PNG_FILE)
rgb = Image.new('RGB', rgba.size, (255, 255, 255))  # white background
rgb.paste(rgba, mask=rgba.split()[3])               # paste using alpha channel as mask
rgb.save(PDF_FILE, 'PDF', resoultion=100.0)

view.py

class Environment(models.Model):
    name = models.CharField(max_length=50)

class Item(models.Model):
    environment = models.ForeignKey(Environment, on_delete=models.CASCADE)
    uid = models.CharField(max_length=50, unique=True, null=True, blank=True)
    def __init__(self):
        super(Item, self).__init__()
        self.uid = str(uuid.uuid4())

forms.py

如果用户填写了class EnvironmentCreateView(CreateView): '''View for creating Environments''' model = Environment form_class = EnvironmentCreateForm template_name = 'Environment_create.html' success_url = reverse_lazy('main:Environment list') 字段,它应该在数据库中生成n个项目。我采用的当前方法有一个覆盖保存功能的问题。不确定我是否需要使用inline_formeset

items

1 个答案:

答案 0 :(得分:0)

我找到了答案,但这是在基于函数的视图中

forms.py 摆脱底部

 class EnvironmentCreateForm(forms.ModelForm):
        name =forms.CharField(max_length=50, required=True, label='Product Name')
        items =forms.IntegerField(min_value =0, max_value = 100,required=False, label='Number of Items')
        class Meta:
            model = Environment
            fields = ['name',]

views.py

def EnvironmentCreateView(request):

    if request.method == 'POST':
        form =  EnvironmentCreateForm(request.POST)
        if form.is_valid():
            name =form.cleaned_data['name']
            items =form.cleaned_data['items']
            env = form.save(commit = False) # this item must be saved first before using the id for the second item
            env.save()
            if units is not None:
                for i in items:
                    Item.objects.create(environment =env)
    else:
            form =  EnvironmentCreateForm()
        return render(request, 'HTMLPAGE.html', {'form': form})