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
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. Bootstrap Accordian by Netplay4 5 years, 3 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 3 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 3 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 4 months ago
  5. Pagination Django with Boostrap by guilegarcia 8 years, 6 months ago

Comments

Please login first before commenting.