如何更改视图中的表单字段属性?

问题描述 投票:0回答:2

我有一个包含四个字段的模型表单,默认情况下只有一个字段处于活动状态等待用户输入。

class SaleOrderInvoiceForm(forms.ModelForm):
  class Meta:
    model = SaleOrderInvoice
     fields = (
      'supplier',
      'sale_order',
      'invoice_number',
      'invoice_date',
      )
     widgets={
      'supplier':forms.Select(attrs={'class':'form-control'}),
      'sale_order':forms.Select(attrs={'class':'form-control', 'disabled':'disabled'}),
      'invoice_number':forms.TextInput(attrs={'class':'form-control', 'disabled':'disabled'}),
      'invoice_date':forms.DateInput(attrs={'class':'form-control','type':'date','disabled':'disabled'}),
        }

根据用户对第一个输入的选择,表单的其余部分通过 AJAX 加载。现在在视图中,经过必要的过滤后,我想将禁用的表单字段切换为启用,将启用的表单字段切换为禁用。我尝试过以下方法,但没有成功。

form = SaleOrderInvoiceForm()
form.fields['supplier'].disabled = True
form.fields['sale_order'].disabled = False
form.fields['invoice_number'].disabled = False
form.fields['invoice_date'].disabled = False

它既不会引发任何异常,也不会按预期工作。 谁能建议解决这个问题的方法吗?

django django-forms
2个回答
0
投票

我找到了解决方案,看来禁用属性无法重置回False,但是可以

pop
出。

    form.fields['supplier'].disabled = 'disabled'
    form.fields['sale_order'].widget.attrs.pop('disabled')
    form.fields['invoice_number'].widget.attrs.pop('disabled')
    form.fields['invoice_date'].widget.attrs.pop('disabled')

0
投票

感谢这篇文章。这非常有用。我试图在文档中找到可以引用此内容的位置。我很难找到它,哈哈。任何人都可以帮助链接到我可以在文档中引用此内容的位置吗?

© www.soinside.com 2019 - 2024. All rights reserved.