我当前的设置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
insideforms.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)
但这没有用;它包括模型上的所有字段。我假设问题出在面向对象上。
欢迎任何提示或建议。提前致谢!