我是 Django 的初学者。我只是迷失了为什么这行不通。
我正在尝试使用 optgroup 及其选项初始化字段
在 views.py 中
class SystemDetailView(DetailView):
"""Detail view for Systems"""
form_class = system_form()
model = System
template_name = 'systems/system_detail.html'
def get_context_data(self, **kwargs):
context = super(SystemDetailView, self).get_context_data(**kwargs)
context.update({
'system_update_form': self.form_class(instance=self.get_object()),
})
return context
def system_form(self):
form= SystemForm
form.fields['primary_purpose_business_use'].choices= list()
for optgroup in BusinessSystemType.objects.all():
form.fields['primary_purpose_business_use'].choices= form.fields['primary_purpose_business_use'].choices.append(
optgroup.name, list(subtype.name for subtype in BusinessSystemType.objects.filter(parent= optgroup))
)
return SystemForm
在表单中
class SystemForm(ModelForm):
"""Form to create and modify systems"""
# only show top-level UserTypes for application_user_type field
application_user_type = ModelChoiceField(
queryset=UserType.objects.filter(parent__isnull=True), required=False,
help_text="Type of user who interacts with the system")
lines_of_business = ModelMultipleChoiceField(
widget=forms.widgets.CheckboxSelectMultiple(), queryset=LineOfBusiness.objects.all(),
required=False, help_text="Identify lines of business this system touches"
)
customer_segments_served = ModelMultipleChoiceField(
widget=forms.widgets.CheckboxSelectMultiple(), queryset=CustomerSegment.objects.all(),
required=False, help_text="Customer segments this resource serves"
)
application_user_sub_type = ModelMultipleChoiceField(
widget=forms.widgets.CheckboxSelectMultiple(), queryset=UserType.objects.filter(parent__name='Internal'),
required=False, label="Internal user type"
)
primary_purpose_business_use = ModelChoiceField(
queryset=BusinessSystemType.objects.filter(parent__isnull=True), required=False,
help_text="primary business purpose")
class Meta:
model = System
fields = ['name', 'short_name', 'accountable_team', 'description', 'lines_of_business',
'business_system_type', 'customer_segments_served',
'application_user_type', 'other_application_user_type', 'application_user_sub_type',
'intellectual_property', 'deployment_model',
'business_criticality', 'service_criticality',
'vendor', 'other_vendor', 'technology_type', 'other_technology_type',
'associated_technologies', 'renewal_date',
'installation_date', 'deprecation_date', 'purchase_price',
'contract_signed_date', 'contract_end_date', 'parimary_purpose_business_use', 'documentation_url', 'notes', 'tags']
我在 form_class = system_form() 中得到 Unresolved 引用 我究竟做错了什么?可能很多。但是你能帮帮我吗?
请您参考如下方法:
form_class = system_form()
事实是,system_form 是一个实例方法。这意味着调用它您需要一个 SystemDetailView 的实例,而您在创建 SystemDetailView 时显然没有。
看来您只需要一个返回类的函数即可分配给 form_class 属性。要将方法转换为函数,只需将其移出类主体即可。您也不需要将 self 作为函数参数。
(另外你的代码显然有一些缩进问题,但我相信你只是复制粘贴错了。)
