字段和base_fields - Django [英] fields and base_fields - Django
问题描述
创建平面图时,我希望用户从预定义的列表中选择一个模板。为了保持 Flatpage
模型不变,我更喜欢 ChoiceField
over ModelChoiceField
(后者提供了模板的PK,但我需要名称为template_name字段):
When creating a flatpage, I want the user to select a template from a predefined list. In order to keep the Flatpage
model untouched, I prefer ChoiceField
over ModelChoiceField
(the latter provides the PK of the template, but I need the name for the template_name field):
class NewFlatpageForm(FlatpageForm):
template_name = forms.ChoiceField(choices = [])
def __init__(self, *args, **kwargs):
self.base_fields['template_name'].choices = ProjectTemplate.objects.values_list('path', 'name')
super(NewFlatpageForm, self).__init__(*args, **kwargs)
我覆盖 __ init __
或Django在服务器启动时填充选项,然后不更新列表。
I override __init__
or Django populates choices at server start and does not update the list then.
我没有任何管理体验,但是当不使用管理员时,我使用字段
属性进行了类似的操作。但是在这种情况下,我得到了一个例外: fields
不是表单的属性。 __ dict __
显示我有一个 base_fields
属性并使用它。所以,为什么在这里使用base_fields,为什么字段
不存在,最后我在做某事hacky?
I don't have any admin experience, but I did similar things using the fields
attribute when not using admin. However in this case, I got an exception telling fields
is not an attribute of the form. __dict__
showed me there's a base_fields
attribute and using it works. So, why use base_fields here, and why is fields
not present and finally am I doing something hacky?
推荐答案
字段
不存在,直到 您调用超级
。所以只是交换线的顺序,所以超级
首先。
fields
doesn't exist until after you've called super
. So just swap the order of the lines, so that super
comes first.
这篇关于字段和base_fields - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!