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})
显然,我认为最佳做法是在OrderDetailForm
内定义forms.py
而不是views.py
。那么如何将OrderDetailForm
移至forms.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)
但那不起作用;它包括模型上的所有字段。我假设问题是在面向对象。
欢迎任何提示或建议。提前谢谢!
答案 0 :(得分:1)
查看Django代码,您可能想尝试使用self._meta.fields = tuple(include_fields)
。
答案 1 :(得分:1)
您必须修改初始化程序中的self.fields
,删除序列中未找到的映射中的键。