我需要帮助在Django表单中使用名为CustomModelChoiceField的自定义字段。我试图重写ModelChoiceField的label_from_instance
方法
我的表格:
from django import forms
from myfolder.otherfolder.fields import CustomModelChoiceField
class MyForm(forms.Form):
# I had to override init to get some paramaters, so I'll simplify it
def __init__(self, *args, **kwargs):
#skipped querying code
self.fields['custom'] = CustomModelChoiceField(queryset = custom_dates,
required = False,
widget = forms.Select(attrs={"onChange":'changeCalendar()'}),
label = "Choose a date")
我的自定义fields.py文件(与forms.py位于同一文件夹中,并且import语句有效)。取自docs:
from django.forms import ModelChoiceField
class CustomModelChoiceField(ModelChoiceField):
def label_from_instance(self, custom_date):
return str(custom_date.end_date)
然后当我尝试查看页面时,我得到:
'module' object has no attribute 'CustomModelChoiceField'
可能是我的fields.py在错误的文件夹中,或者我在子类化时很糟糕。有什么想法吗?