我有以下两个模型
class ModelOne(models.Model):
mod_desc = models.CharField(max_length=25)
is_active = models.BooleanField(default=True)
class ModelTwo(models.Model):
another_desc = models.CharField(max_length=25)
is_active = models.BooleanField(default=True)
modone = models.ForeignKey(ModelOne)
以下是ModelTwoAdmin的管理员代码
class ModelTwoAdmin(admin.ModelAdmin):
def formfield_for_foreignkey(self,db_field,request, **kwargs):
if db_field.name == 'modone':
kwargs['queryset'] = ModelOne.objects.exclude(is_active=False)
fieldsets = [
('String 1', {'fields' : ['another_desc','modone']}),
('String 2', {'fields' : ['is_active']}),
]
我的目标是过滤掉is_active
为False
的ModelOne条目。但是,上面的代码返回错误 - 第7行在堆栈跟踪中突出显示,但代码块中包含**
:
Django Version: 1.4
Exception Type: KeyError
Exception Value:
"Key 'modone' not found in Form"
Exception Location: c:\Python\Python2.7\App\lib\site-packages\django\forms\forms.py in __getitem__, line 109
1 <fieldset class="module aligned {{ fieldset.classes }}">
2 {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
3 {% if fieldset.description %}
4 <div class="description">{{ fieldset.description|safe }}</div>
5 {% endif %}
6 {% for line in fieldset %}
**7 <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}">**
8 {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
9 {% for field in line %}
10 <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}>
11 {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
12 {% if field.is_checkbox %}
13 {{ field.field }}{{ field.label_tag }}
14 {% else %}
15 {{ field.label_tag }}
16 {% if field.is_readonly %}
17 <p>{{ field.contents }}</p>
如何过滤掉不活跃的ModelOne
?
答案 0 :(得分:1)
问题是您指定了两次None
字段集。第二个是覆盖第一个,因此表单中唯一的字段是is_active
。给第二个None
一个实际的字符串名称,或者只将两个字段集合并为一个。
答案 1 :(得分:1)
formfield_for_foreignkey
方法中缺少return语句。 return语句应为:
return super(ModelTwo, self).formfield_for_foreignkey(db_field, request, **kwargs)