0

我有以下两种型号

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']}),
    ]

我的目标是过滤掉 ModelOne 条目 where is_activeis False。然而,上面的代码返回了一个错误——第 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的s?

4

2 回答 2

1

问题是您指定了一个None字段集两次。第二个覆盖第一个,因此表单中的唯一字段是is_active. 给第二个None一个实际的字符串名称,或者只是将两个字段集合并为一个。

于 2012-08-08T15:12:55.650 回答
1

方法中缺少 return 语句formfield_for_foreignkey。返回语句应该是:

return super(ModelTwo, self).formfield_for_foreignkey(db_field, request, **kwargs)
于 2012-08-08T16:50:49.980 回答