1

我当前的设置views.py如下所示

def order_detail(request, pk):
    order = Order.objects.get(pk=pk)

    # Define the can_something variables here.

    include_fields = []

    if can_edit_work_type:
        include_fields.append('work_type')
    if can_edit_vendor:
        include_fields.append('vendor')
    if can_edit_note:
        include_fields.append('note')

    class OrderDetailForm(forms.ModelForm):
        class Meta:
            model = Order
            fields = tuple(include_fields)

    form = OrderDetailForm(instance=order, data=request.POST)

    return render(request, 'doors/order/detail.html', {'order': order, 'form': form})    

显然,我认为最好的做法是定义OrderDetailForminsideforms.py而不是views.py. 那么我如何移动OrderDetailFormforms.py仍然通过include_fields

我尝试过这样的事情,但没有奏效

views.py

def order_detail(request, pk):
    order = Order.objects.get(pk=pk)

    # Define the can_something variables here.

    include_fields = []

    if can_edit_work_type:
        include_fields.append('work_type')
    if can_edit_vendor:
        include_fields.append('vendor')
    if can_edit_note:
        include_fields.append('note')

    form = OrderDetailForm(instance=order, data=request.POST, include_fields=include_fields)

    return render(request, 'doors/order/detail.html', {'order': order, 'form': form})    

forms.py

class OrderDetailForm(forms.ModelForm):
    class Meta:
        model = Order

    def __init__(self, include_fields, *args, **kwargs):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        self.Meta.fields = tuple(include_fields)

但这没有用;它包括模型上的所有字段。我假设问题出在面向对象上。

欢迎任何提示或建议。提前致谢!

4

2 回答 2

1

查看 Django 代码,您可能想尝试使用self._meta.fields = tuple(include_fields).

于 2012-05-18T23:44:31.990 回答
1

您必须在初始化程序中进行修改self.fields,删除序列中未找到的映射中的键。

于 2012-05-19T03:59:23.883 回答