这可能更像是一个OO Python问题。但它来自this question我问过Django。
所以@burhan建议我不要手动在我的Django模板中写出自定义<select>
和<option>
标记,而应该使用自定义ModelChoiceField
和forms.Select
。
我当前继承ModelForm
并为我的模型OrderCreateForm
创建一个名为Order
的自定义表单,creator
的{{1}}基于queryset
{1}} creator
因此我需要以某种方式将变量传递给自定义user_type
以在自定义ModelForm
中使用。
所以我最终想要这样的东西
ModelChoiceField
我知道在类中创建参数与class OrderCreateForm(ModelForm):
class Meta :
model=Order
fields=('work_type', 'comment',)
def __init__(self):
# somehow get a variable called user_type
if user_type == 'foo':
queryset = User.objects.all()
else:
queryset = User.objects.filter(userprofle__user_type='bar')
creator = MyCustomField(queryset=queryset,
empty_label="Please select",
widget=forms.Select(attrs={'onchange':'some_ajax_function()'})
有关,但我是OO新手,我不确定创建自己的__init__
是否会与{{1}冲突}}。另外,我想调用我的自定义__init__
类ModelForm.__init__
。那可能吗。
很抱歉,如果我的问题令人困惑,就像我说我是OO新手一样,我不太了解所有的术语和概念。
编辑:以下是Django关于ModelForm
的一些源代码:
form=OrderCreateForm(user_type='foo_bar')
答案 0 :(得分:2)
您很可能需要在OrderCreateForm
中初始化ModelFormclass OrderCreateForm(ModelForm):
class Meta :
model=Order
fields=('work_type', 'comment',)
# *args and **kwargs will help you to main the compatibility with your parent
# class without to manage all arguments
def __init__(self, user_type, *args, **kwargs):
# ModelForm.__init__(self, *args, **kwargs)
# Usage of super is recommended.
super(OrderCreateForm, self).__init__(*args, **kwargs)
self.user_type = user_type
if self.user_type == 'foo':
queryset = User.objects.all()
else:
queryset = User.objects.filter(userprofle__user_type='bar')
self.creator = MyCustomField(
queryset=queryset,
empty_label="Please select",
widget=forms.Select(attrs={'onchange':'some_ajax_function()'})
)
这就是你需要的吗?
霍尔迪阿