4

这个问题中,我想将我的表单从常规转换Form为,ModelForm以便我可以利用instance参数 in ModelForm

这是我当前的表单代码:

class OrderDetailForm(forms.Form):
    def __init__(
        self,
        user,
        can_edit_work_type=None,
        can_edit_vendor=None,
        can_edit_note=None,
        *args,
        **kwargs
    ):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        if can_edit_work_type:
            self.fields['work_type'] = forms.ChoiceField(choices=Order.WORK_TYPE_CHOICES)
        if can_edit_vendor:
            self.fields['vendor'] = forms.ModelChoiceField(
                queryset=Vendor.objects.all(),
                empty_label="Choose a vendor",
            )
        if can_edit_note:
            self.fields['note'] = forms.CharField(widget=forms.Textarea)

    def clean(self):
        super(OrderDetailForm, self).clean()

        if 'note' in self.cleaned_data:
            if len(self.cleaned_data['note']) < 50:
                self._errors['note'] = self.error_class([u"Please enter a longer note."])

                del self.cleaned_data['note']

        return self.cleaned_data

如您所见,我有一些if语句可以确定字段是否甚至在表单中显示(从逻辑上讲,这意味着某些用户只能编辑字段的某些部分)。

我该怎么做ModelForm?我知道fields是一个元组,所以它不能像我在Form. 所以我想做类似的事情

class OrderDetailForm(forms.ModelForm):
    class Meta:
        model = Order
        # fields = ('work_type', 'vendor', 'note') I can't do that since I need to be able to control it. See below.

        # Can I control widgets even if that field doesn't exist?
        widgets = {
            'note': forms.Textarea(),
        }

    def __init__(
        self,
        user,
        can_edit_work_type=None,
        can_edit_vendor=None,
        can_edit_note=None,
        *args,
        **kwargs
    ):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        fields = []

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

        self.Meta.fields = tuple(fields) # Does this work?

    def clean(self):
        super(OrderDetailForm, self).clean()

        if 'note' in self.cleaned_data:
            if len(self.cleaned_data['note']) < 50:
                self._errors['note'] = self.error_class([u"Please enter a longer note."])

                del self.cleaned_data['note']

        return self.cleaned_data

那可能吗?您如何控制 中的字段ModelForm

4

2 回答 2

5

另一种可能的方式是在视图中生成一个内联表单类,以根据请求排除字段,例如,为 Order 模型定义一个普通的模型表单,称为 OrderDetailForm:

class OrderDetailForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = ('work_type', 'vendor', 'note') 
        widgets = {
            'note': forms.Textarea(),
        }

在视图中,例如编辑订单,根据 OrderDetailForm 创建自定义表单:

def edit(request, order_id):
    order = Order.objects.get(pk=order_id)
    can_edit_work_type = bool(request.REQUEST.get('can_edit_work_type', False))
    can_edit_vender = bool(request.REQUEST.get('can_edit_vender', False))
    can_edit_note = bool(request.REQUEST.get('can_edit_note', False))

    exclude_fields = []

    if not can_edit_work_type:
        exclude_fields.append('work_type')

    if not can_edit_vender:
        exclude_fields.append('vender')

    if not can_edit_note:
        exclude_fields.append('note')

    class CustomizedOrderForm(OrderDetailForm):
        class Meta:
            model = Order
            exclude = tuple(exclude_fields)

    if request.method == 'POST':
        form = CustomizedOrderForm(instance=order, data=request.POST)
        if form.is_valid():
            form.save()
    else:
        form = CustomizedOrderForm(instance=order)
    return render(request, 'order_form.html', {'form': form})
于 2012-05-18T04:04:21.493 回答
2

ModelFormapi 与常规的 api 非常相似Form。优点是除了默认小部件、实例 kwarg 和保存方法等便利之外,您现在还可以获得模型验证

fields attr仍然dict像。您可以在此处看到由元类构建的字段。然后,通过继承和调用,我们到达声明的字段中的a最初是 a 。这对于和的两个子类很常见。super()BaseModelForm.__init__deepcopySortedDictFormModelFormBaseForm

将字段放在排除项中,并按照您在原始文件中的方式添加它们__init__

以同样的方式清洁它们。

然后,您可以覆盖该save方法:您可以调用super()以取回对象并根据cleaned_data需要处理数据。

class OrderDetailForm(forms.ModelForm):
    # regular fields, not based on bools
    # ...

    class Meta:
        model = Order
        exclude = ('work_type', 'vendor', 'note')
        # or fields = (...other fields )


    def __init__(
        self,
        user,
        can_edit_work_type=None,
        can_edit_vendor=None,
        can_edit_note=None,
        *args,
        **kwargs,
    ):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        if can_edit_work_type:
            self.fields['work_type'] = forms.ChoiceField(
                                       choices=Order.WORK_TYPE_CHOICES)
        if can_edit_vendor:
            self.fields['vendor'] = forms.ModelChoiceField(
                queryset=Vendor.objects.all(),
                empty_label="Choose a vendor",
            )
        if can_edit_note:
            self.fields['note'] = forms.CharField(widget=forms.Textarea)

    def clean(self):
        # I never call super() in clean .. do I? .. hmmm
        # maybe I should or is sth magic going on?
        # alternately,
        # data = self.cleaned_data
        # let's call super though
        data = super(OrderDetailForm, self).clean()

        if 'note' in data:
            if len(data['note']) < 50:
                # I raise a validation error so .is_valid() comes back False
                # form.errors happens magically ...
                raise forms.ValidationError("Not long enough ...")

        return data

    def save(self, *args, **kwargs):
        data = self.cleaned_data
        # maybe do some stuff here
        # ...

        # commit=True or commit=False could be important
        order = super(OrderDetailForm, self).save(*args, **kwargs)

        if 'note' in data:
            order.note = data['note']

        # ... do other stuff

        # probably ...
        order.save()

        # respect how model forms work.
        return order
于 2012-05-18T03:13:23.703 回答