Login

Making prepopulate_from work with ForeignKeys and other sorts of choice fields

Author:
josho
Posted:
September 16, 2008
Language:
HTML/template
Version:
Not specified
Tags:
javascript admin prepopulate
Score:
0 (after 0 ratings)

This is a fairly small bit template that, if placed in your_project_dir/templates/admin/prepopulated_fields_js.html will override the template that is normally pulled by the preopulated fields templatetag in the admin. The result is that you can successfully specify a ForeignKey or other field involving choices as a source for prepopulate_from in your admin.py. It works just as well when there are multiple fields of both the text and choice variety.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<script type="text/javascript">
    {% for field in prepopulated_fields %}
    document.getElementById("{{ field.field.auto_id }}").onchange = function() { this._changed = true; };
    {% for dependency in field.dependencies %}
document.getElementById("{{ dependency.auto_id }}").{% if dependency.field.choices %}onchange{% else %}onkeyup{% endif %} = function() {
    var e = document.getElementById("{{ field.field.auto_id }}");
    if (!e._changed) {
        e.value = URLify({% for innerdep in field.dependencies %}{% if innerdep.field.choices %}document.getElementById("{{ innerdep.auto_id }}").options[document.getElementById("{{ innerdep.auto_id }}").selectedIndex].text{% else %}document.getElementById("{{ innerdep.auto_id }}").value{% endif %}{% if not forloop.last %} + ' ' + {% endif %}{% endfor %}, {{ field.field.field.max_length|default_if_none:"50" }});
    }
}
    {% endfor %}
{% endfor %}
</script>

More like this

  1. Filtering foreignkey fields in django admin by forgems 6 years, 2 months ago
  2. Auto slug field by GaretJax 7 years, 4 months ago
  3. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 4 years, 11 months ago
  4. ForeignKey filterspec by luc_j 4 years, 11 months ago
  5. Hyperlink read-only ForeignKey objects in admin to their change pages by strangefeatures 3 years, 7 months ago

Comments

Please login first before commenting.