Cerin
Cerin

Reputation: 64739

Customizing a Django Form Field in Admin Based on Value

How do you customize the display of a form in Django's admin based on a form field's value? For example, I have a field whose default value is "0". If the field has been set to a non-zero value, I want to show an additional "Edit" link on the form, which would link to a separate page allowing edit other fields related to a related model. I've found how to customize admin's form template, but I can't find how to access a form field's actual value in order to add the if/else statement in the template.

I've tried digging through the source code, and I've traced my field instance to django.contrib.admin.AdminField.field->django.forms.BoundField but displaying the BoundField's field and data attribute doesn't show the value stored in the default form field widget markup. How do I access a specific field's data value inside a template so I can do something like the following?

{% for fieldset in inline_admin_form %}
    {% for line in fieldset %}
        {% for field in line %}
            {{field.field}} {% if field.field.value != 0 %}<a href="/some/path/to/model/{{field.value}}">Edit</a>{% endif %}
        {% endfor %}
    {% endfor %}
{% endfor %}

Upvotes: 2

Views: 1521

Answers (1)

Just did a shell session typing in random variables (ipython ftw) and found this:

boundfield.data = data
boundfield.field.initial = initial

{% for field in form %}
   {% if field.data != field.field.initial %}Not Initial{% endif %}
{% endfor %}

Give it a shot!

Upvotes: 1

Related Questions