【问题标题】:Change form dynamically in django在 django 中动态更改表单
【发布时间】: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


    【解决方案1】:

    我会使用一个基本表单类,并从基本表单继承两种不同的表单。您可以根据用户输入通过 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)
    

    有意义吗?

    【讨论】:

    • 当我调用 simpleFormA 时,它会在 forms.py 行中引发Caught NameError while rendering: name 'self' is not definedself.fields["chosen_method"].choices = _a_choices
    • 这个帖子帮助我解决了过去一天我试图自己解决的问题。谢谢你们!
    猜你喜欢
    • 2017-06-06
    • 1970-01-01
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多