Django Ajax请求

6 投票
1 回答
1622 浏览
提问于 2025-04-17 17:30

我在用Ajax发送表单时遇到了问题。我有一个表单,想在点击“下一步”按钮时,异步地用另一个表单替换掉它。

下面是我的脚本

$(document).ready(function() {
    $('#MY_FORM').submit(function() { 
        $.ajax({
            data: $(this).serialize(), 
            type: $(this).attr('method'),
            url: $(this).attr('action'), 
            success: function(response) { 
                $('#FORM_DIV').html(response); 
            }
        });
        return false;
    });
});

form.py

class CountyForm(forms.Form):
    county = forms.ModelChoiceField(queryset=County.objects.all(),
              empty_label='---Select a county---', required=False)
    other = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        super(CountyForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.html5_required = True
        self.helper.form_id = 'MY_FORM'
        self.helper.add_input(Submit('next', 'Next', css_class='classfinish'))
        self.helper.layout = Layout('county','other')


class WardForm(forms.Form):
    ward = forms.ModelChoiceField(queryset=Ward.objects.all(),
             empty_label='Select a ward')
    other = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(WardForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.html5_required = True
        self.helper.add_input(Submit('save', 'Finish'))
        self.helper.add_input(Submit('cancel', 'Cancel'))
        self.helper.layout = Layout('ward','other')

视图

def location(request):
    if request.is_ajax() :
        wardform = WardForm()
        return HttpResponse(wardform)
    countyform = CountyForm()
    c = {}
    c.update(csrf(request))
    return render(request,'location.html', {'countyform': countyform})

我希望在县的表单中点击“下一步”按钮时,能够显示出区的表单。

1 个回答

1

这个问题可以用两种方法来解决,我不会详细讲解FormWizard,但我会给你一个很好的文档链接。

我建议你使用FormWizard(这取决于你使用的Django版本),我记得它是在Django 1.2及之后的版本中引入的,但具体情况我不敢保证。

在你目前的情况下,你可以尝试以下方法。

$(document).ready(function() {
    $('#MY_FORM').submit(function() { 
        $.ajax({
            data: $(this).serialize(), 
            type: $(this).attr('method'),
            url: $(this).attr('action'), 
            success: function(response) { 
                $('#FORM_DIV').load('/some/url/to/a/wardform'); //new code 
            }
        });
        return false;
    });
});

views.py

def ward_form_renderer(request):
    if request.is_ajax():
        ward_form = WardForm()
        #depending on version of django
        context = {'wardform': ward_form}
        context.update(csrf(request))
        render(request, 'wardform_template', c)

这样做的效果是,它会从你的Django视图中拉取一个新的HTML页面,并显示一个渲染好的表单。基本上,你做的就是一个FormWizard。不过,这种方法会有其他副作用,所以我不推荐这样做。

我自己也在一个项目中使用了这种方法,老实说,更多的是麻烦而不是乐趣。我自己没有试过这段代码,但你应该能理解它的工作原理。

这时候就要提到FormWizard了!这是一个特别适合你的选择,因为你不需要重新定义你的表单,可以直接使用现有的。

这是FormWizard文档的链接

祝你好运!

撰写回答