1

Description: I have created a page. The page is running on http://127.0.0.1:8000/. There are three forms. I have one button separately. When I click on that button, all three form values need to be collected in Django view.py. But I'm having a problem with ajax request-response. The value arry1D is not getting at the Django view.py

Below is the separate button.

<form method="post">
  {% csrf_token %}
  <input class="bg-yellow text-white" value="RUN" name="runModel" type="submit" 
   onclick="sendValuesToBack()">
</form>

Below is the JavaScript Method.

            function sendValuesToBack()
            {
                let j,
                    i,
                    arry1D = [];

                for(j=0;j!=countName;j++)
                {
                    var inputs = document.getElementById("formId" + j).elements;
                    if (!arry1D[j]) arry1D[j] = []
                    arry1D[j][0] = "formId" + j;

                    console.log("---------------Form--------------------");
                    for (i = 0; i < inputs.length; i++) {
                        if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") {
                            console.log("values of form:", inputs[i].value);
                            arry1D[j][i + 1] = inputs[i].value;
                        }
                    }
                }
                var tk = $(this).attr("data-token")
                $.ajax({
                    url: "/",
                    type:"POST",
                    data:
                        {   'arry1D':arry1D,
                            'csrfmiddlewaretoken': tk},
                    cache:false,
                    dataType: "json",
                    success: function(resp){
                        alert ("resp: "+resp.arry1D);
                    }
                });
            }

view.py --> function from Django

    if request.method == "POST" and request.is_ajax():
        arry1D = request.POST.get('arry1D')
        return HttpResponse(json.dumps({'arry1D': arry1D}), content_type="application/json")

url.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name="index"),
    path('',views.getModelAttribute,name="index"),
]

Error

Internal Server Error: /form-post
Traceback (most recent call last):
  File "C:\Users\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\views.py", line 39, in getModelAttribute
    return JsonResponse(json.dumps({'arry1D': arry1D}), content_type="application/json")
AttributeError: module 'django.core.serializers.json' has no attribute 'dumps'
[24/Jun/2020 15:34:30] "POST / HTTP/1.1" 200 16236

4
  • Are you getting any errors? It appears you have two routes named "index" there, too, pointing to the same URL path. Commented Jun 24, 2020 at 21:55
  • So, I'm new to Django and ajax. The first URL is for getting the index page. In the second one, All three form values are coming from the same page that's why I wrote it. Should i write anything else? Commented Jun 24, 2020 at 22:01
  • Yes. do path('/form-post/', views.getModelAttribute, name="form_post") or something, then in your javascript put url: '{% url 'form_post' %}'; if that is the method you are posting the data to. Commented Jun 24, 2020 at 22:03
  • 1
    @MichaelHawkins yeah, you are right! I checked the jQuery Docs, this header is automatically added Commented Jun 24, 2020 at 22:16

1 Answer 1

1

You have multiple routes with the same name. Update the URLs to something like this instead (assuming the one named "form_post" is where you are sending the form data):

urlpatterns = [
    path('admin/', admin.site.urls),
    path('/',views.index,name="index"),
    path('/form-post/',views.getModelAttribute,name="form_post"),
]

Then, in your javascript in the template:

                $.ajax({
                    url: "{% url 'form_post' %}",
                    type:"POST",
                    data:
                        {   'arry1D':arry1D,
                            'csrfmiddlewaretoken': tk},
                    cache:false,
                    dataType: "json",
                    success: function(resp){
                        alert ("resp: "+resp.arry1D);
                    }
                });

Lastly, use JSONResponse() instead of HttpResponse() when sending data back.

Sign up to request clarification or add additional context in comments.

6 Comments

Hey! Michael. Thank you very much. I got the value of that variable on the django side. But I'm getting [24/Jun/2020 15:27:21] "POST / HTTP/1.1" 200 16217 Internal Server Error: /form-post error
What is the error from the console? Need the entire error. Also post the full updated view code if you can.
I have added the error in the question. Please have a look at it.
Just pass the raw data to JSONResponse - return JSONResponse({'arry1D':arry1D}) and remove the "content type" portion. It is not needed.
Awesome sir. Finally, It worked. Thank you very much, Michael, you completely saved me.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.