I have the following two models
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)
And the following admin code for 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']}),
]
My goal is to filter out ModelOne entries where is_active is False. However, the above code returns an error – line 7 is highlighted in the stack trace but in code blocks here is surrounded with **:
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>
How can I filter out the inactive ModelOnes?
The return statement was missing from the
formfield_for_foreignkeymethod. The return statement should be: