【发布时间】:2012-02-28 12:13:39
【问题描述】:
有办法通过 ajax 加载 django 表单吗?假设用户需要根据他的需要更改表单。首先出现一个带有选择域和小数域的表单。然后,根据选择字段的值,对视图的 ajax 请求可以将其更改为另一种形式或保持不变:
forms.py
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()
我尝试像这样的 ajax 方式,它会观察选择字段值 (#id_chosen_method) 的变化:
ajax_form.js
(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);
最后是获取javascript函数传递的“method”参数的url和view:
#url.py
url(r'^/form2/(?P<method>\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
所以最终的想法是用户根据首先显示的选择字段的值来选择想要的表单。但我不能让它工作。我错过了什么吗?有更好的方法来处理这样的事情吗?
【问题讨论】:
标签: jquery django django-forms