Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django ajax request

I am having a problem sending a form with Ajax. I have a form which i want to replace with another form asynchronously on clicking the next button.

Here is the script

$(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')

views

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})

I want when i click next button in the county form, the ward form to appear.

like image 672
Alexxio Avatar asked Feb 28 '13 23:02

Alexxio


People also ask

How do you make a dynamic dropdown list with AJAX in Django?

To make an Ajax request, we first need to include the jquery library to our page. We define id = "question-subject" to our subject dropdown list. We select this list with the jquery selector and detect a change in this list with the change event. We assign the ID of the selected subject to a variable.

How Django save data from AJAX database?

Create the AJAX View POST to the form—this is known as binding a form to a dataset. Next, we check the form to see if the submitted data is valid. Django validates the data behind the scenes for us. If the data is correct, we save the form to the database with form.


1 Answers

This could be solved in two ways, I won't cover FormWizard but I'll give you the link to the documentation which is really good.

My recommendation is that you should go for a FormWizard (depending on what version of Django you have) but I think it was migrated into Django at 1.2 and onwards but don't quote me on that.

In you current predicament you should do something along the lines of this.

$(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)

What this will do is that it will pull a new html page with a rendered form from your Django view and display it. Basically what you've then done is a FormWizard. This approach will have other side effects so I wouldn't recommend doing it this way.

I myself is in a project that does this and it's more pain than pleasure to be honest. I haven't tried this code myself but you get the gist of how it should work.

Enter FormWizard! This is particular good choice for you since you dont have to redefine your forms, you can use the ones you have.

Here's the link to the FormWizard docs

Good luck!

like image 101
Henrik Andersson Avatar answered Oct 16 '22 22:10

Henrik Andersson