Jainish Dabhi
Jainish Dabhi

Reputation: 35

Passing Values from JavaScript to Django view.py

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

Upvotes: 1

Views: 69

Answers (1)

Michael Hawkins
Michael Hawkins

Reputation: 2873

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.

Upvotes: 1

Related Questions