[Django]-Django dynamic forms – on-the-fly field population?

6👍

Here is one approach – Django/jQuery Cascading Select Boxes?

You can create a new view that just renders json to a string,
and then trigger an event when you’re done selecting from the first list which loads the data dynamically from that json.

3👍

I do a similar thing here, populating a form based on a selection in a drop down. Maybe this helps you.

Here is the model of the values used to pre-populate the form:

class OpmerkingenGebrek(models.Model):
    opmerking = models.CharField(max_length=255)
    advies = models.CharField(max_length=255)
    urgentiecodering = models.CharField(max_length=2, choices=URGENTIE_CHOICES_2011)
    bepaling = models.CharField(max_length=155,blank=True,null=True)
    aard = models.CharField(max_length=3, choices=AARD_CHOICES)

The view that manages the form:

def manage_component(request,project_id,.....):
    # get values for pre-populate
    og = OpmerkingenGebrek.objects.all()
    .........
    formset = ComponentForm(request.POST,request.FILES)
    .........
        )))
    return render_to_response(template, {
        'formset':formset,
        ........
        'og':og,
        },context_instance=RequestContext(request))

The html the renders the form

{% extends "base.html" %}
{% block extra_js %}
<script type="text/javascript" src="/media/js/limitText.js"></script>
<script type="text/javascript" src="/media/js/getValueOpmerking.js"></script>
{% endblock %}
<form enctype="multipart/form-data" method="post" action="">
{{ formset.as_table }}
</form>

<p>Choose default values:</p>
<select id="default" onChange="getValue(this)">
    {% for i in og %}
    <option value="{{ i.opmerking }} | {{ i.advies }} |  {{ i.urgentiecodering }} | 
    {{ i.aard }} | {{ i.bepaling }}">{{ i.opmerking }}</option>
    {% endfor %}
</select>

The javascript that pre-populates the form:

function getValue(sel)

  {
    //get values
    var opm = sel.options[sel.selectedIndex].value;
    //split string to parts
    var parts = opm.split("|");
    // autofill form
    var opmerking = document.getElementById("id_opmerking");
    opmerking.value = parts[0];
    var aanbeveling = document.getElementById("id_aanbeveling");
    aanbeveling.value = parts[1];
    var opt = document.getElementById("id_urgentie");
    var urgentie = opt.selectedIndex;
    for(var i=0;i<opt.length;i++){
        if(opt.options[i].value == parts[2].split(' ').join('')){
            opt.selectedIndex = i;
       }};

    var opt = document.getElementById("id_aard");
    var aard = opt.selectedIndex;
    for(var i=0;i<opt.length;i++){
      if(opt.options[i].value == parts[3].split(' ').join('')){
          opt.selectedIndex = i;
          }};

    var bepaling = document.getElementById("id_bepaling");
    bepaling.value = parts[4];
  };

Leave a comment