[Answer]-Django, How do I write views when form submission using ajax jquery?

1👍

A simple version not utilizing your models (I’ll leave that up to you as an exercise)

def my_ajax_view(request):
    if request.is_ajax():
        if request.method == 'POST':
            //do you logic here
            response_data = {'success': 'weee'}
            return HttpResponse(json.dumps(response_data), content_type="application/json")
        else:
            return HttpResponseForbidden()
    return HttpResponseForbidden() 

This is how you write a normal function ajax view.
Now to the errors that you’re having.
Firstly I would recommend you not naming your variables mc, mmo, ans, ci or func, basically this makes it 100 times harder for anyone (even you cause you’ll forget in a day what you wrote) to debug.

Secondly you’re using getlist() on the POST. This will give you a list containing the information and when you try to save it your IntegerField mbleno is expecting an integer or string instead of a list.

I would try to switch

mno=request.POST.getlist('mbleno')

to

mno=request.POST.get('mbleno')

which most likely will give you other errors, but it’s a good start!

Leave a comment