Note that there are some explanatory texts on larger screens.

plurals
  1. POChange form dynamically in django
    text
    copied!<p>There's a way to load a django form trough ajax? Let's say an user needs to change a form depending on what he want. First a form with a choicefield and a decimalfield appears. Then ,depending on the value of the choicefield, an ajax request to a view can change it to another form or stay the same:</p> <p>forms.py</p> <pre><code>a_choices = ( ("a", "A"), ("b", "B"), ("c", "C"), ) d_choices = ( ("d", "D"), ("e", "E"), ) class simpleForm(forms.Form): #this is the first form def __init__(self, *args, **kwargs): choices = kwargs.pop('method') super(simpleForm, self).__init__(*args, **kwargs) self.fields["chosen_method"].choices = choices chosen_method = forms.ChoiceField(label="Método") simple_variable = forms.DecimalField() class complexForm(simpleForm): second_variables = forms.DecimalField() third_variable = forms.DecimalField() </code></pre> <p>I try an ajax way like this, who watches the choicefield value (#id_chosen_method) for a change:</p> <p>ajax_form.js</p> <pre><code>(function ($) { explanation = function () { $("#id_chosen_method").change(function () { var election = $("#id_chosen_method").val(); // Add or remove fields depending of method chosen $.getJSON("/form2/" + election + "/", function (data) { if (data) { $("#form_fields").html(data.form); $("#explanation_text").html(data.explanation); } else { $("#form_fields").html("no form!"); $("#explanation_text").html("no explanation!"); } }); }); }; })(jQuery); </code></pre> <p>Finally the url and the view who get the "method" argument passed by the javascript function:</p> <pre><code>#url.py url(r'^/form2/(?P&lt;method&gt;\w+)/$', ajax_form, name='ajax_form'), #views.py def ajax_form(request, method): import json from app.forms import simpleForm, complexForm from app.otherFile import explanations if request.is_ajax: form_choices = (("a", "b", "c",),("f", "g")) if method in form_choices[0]: if method == form_choices[0][-1]: form = simpleForm(method=a_choices) else: form = simpleForm(method=d_choices) else: if method == form_choices[1][1]: form = complexForm(method=a_choices) else: form = complexForm(method=d_choices) explanation = explanations[method] data = {"form": form, "explanation": explanation} return HttpResponse(json.dumps(data), mimetype="application/javascript") else: raise Http404 </code></pre> <p>So the final idea is the user choosing what form wants depending on the val of the choicefield showed in the first place. But i can't get this to work. Am i missing something? there's a better way to handle things like this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload