从视图传递模型到表单的内部Meta类

时间:2019-10-01 13:51:30

标签: python django

我想将特定的模型从视图传递到表单的内部Meta类:

视图:

@login_required
def product_create_view(request):
    if request.method == 'POST':
        create_product_form = CreateProductForm(request.POST, request=request, model=model)
        if create_product_form.is_valid():
            create_product_form.save()
    else:
        create_product_form = CreateProductForm(request=request, model=model)
    return render(request, 'products/product_create.html', {'form': create_product_form})

表格:

class CreateProductForm(ModelForm):

    class Meta:
        model = CreateProductForm.model
        fields = (
            'title',
            'description',
            'price',
            'stock',
            'category'
        )

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        self.model = kwargs.pop('model')
        super().__init__(*args, **kwargs)

有可能吗?

1 个答案:

答案 0 :(得分:0)

这将不起作用,因为在加载文件时会创建带有其字段的表单。您可能可以将类定义移到函数中并动态定义它。

@login_required
def product_create_view(request):

    class CreateProductForm(ModelForm):
        class Meta:
            model = model
            fields = (
                'title',
                'description',
                'price',
                'stock',
                'category'
            )

    if request.method == 'POST':
        create_product_form = CreateProductForm(request.POST, request=request)
        if create_product_form.is_valid():
            create_product_form.save()
    else:
        create_product_form = CreateProductForm(request=request)
    return render(request, 'products/product_create.html', {'form': create_product_form})

我还没有尝试过。