gpt4 book ai didi

python - 如何在 Django 外部设置 ModelForm 中的字段?

转载 作者:行者123 更新时间:2023-12-01 06:00:34 25 4
gpt4 key购买 nike

我当前在 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})

显然,我认为最好的做法是在 forms.py 中定义 OrderDetailForm 而不是 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)

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

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

最佳答案

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

关于python - 如何在 Django 外部设置 ModelForm 中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10660994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com