1
有一種方式來加載一個Django成槽AJAX?比方說,用戶需要根據自己需要更改表單。首先出現帶有選擇字段和小數字段的表單。然後,取決於choicefield的價值,在視圖中的Ajax請求可以將其更改爲另一種形式或保持不變:變化形式動態地在Django
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的方式,誰手錶的變化choicefield值(#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);
最後的URL和視圖誰得到由javascri通過了「法」的說法PT功能:
#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
所以最終的想法是用戶選擇都想取決於choicefield的VAL顯示在第一位什麼樣的形式。但我無法得到這個工作。我錯過了什麼嗎?有更好的方法來處理這樣的事情嗎?
當我打電話simpleFormA它提出了一個 '陷入NameError而渲染:名 '自我' 是不是在forms.py線defined' : 'self.fields [ 「chosen_method」] =選擇_a_choices' – aldeano 2012-02-07 23:52:14
編輯我的代碼,請嘗試使用此代替 – akhaku 2012-02-11 23:43:17
這個線程幫助我解決了一個問題,我試圖在過去一天自己找出問題。感謝你們! – mudda 2015-06-25 17:01:49