在django中动态更改表单

时间:2012-02-07 01:47:50

标签: jquery django django-forms

有一种方法可以通过ajax加载django表单吗?假设用户需要根据他的需要更改表单。首先出现带有choicefield和decimalfield的表单。然后,根据choicefield的值,对视图的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和视图:

#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

所以最后的想法是用户根据首先显示的选择字段的val选择想要的形式。但我不能让这个工作。我错过了什么吗?有更好的方法来处理这样的事情吗?

1 个答案:

答案 0 :(得分:2)

我会使用基本表单类,并且从基本表继承两种不同的表单。您可以根据用户输入通过ajax加载不同的表单。您甚至可以为表单使用相同的模板。您的观点会有类似

的内容
form=simpleFormA()

form=simpleFormB()

基于'方法'是什么。 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
    # all other fields here
    simple_variable = forms.DecimalField()

class simpleFormA(simpleForm):
    chosen_method = forms.ChoiceField(label="Método", choices=_a_choices)

class simpleFormB(simpleForm):
    chosen_method = forms.ChoiceField(label="Método", choices=_b_choices)

有意义吗?