1

I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.

I want to have the ability to, when a user clicks a button, send this javascript object to django so that it can be parsed and handled appropriately. I did a lot of research and found a bunch of similar implementation which use a combination of JQuery and ajax to POST a JSON string. This is some of my code currently:

mainapp/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')),
    url(r'^NetworkTopology/json/', include('OpenAutomation.NetworkTopology.urls')),
    url(r'^admin/', admin.site.urls),
]

NetworkTopology/urls.py

from django.conf.urls import url

from . import views

    urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^json/$', views.returnjson, name='returnjson'),
]

NetworkTopology/views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response


def index(request):
    return render_to_response('index.html')


def returnjson(request):
    if request.is_ajax():
        request_data = request.POST
        print("Raw Data: " + request_data.body)
        return HttpResponse("OK")

JavaScript function (return JSON button is pressed):

function returnJsonTop(){
            $(document).ready(function() {
                $.ajax({
                    method: 'POST',
                    url: '/NetworkTopology/json',
                    dataType: 'json',
                    data: JSON.stringify(nodes.get(),null,4),
                    success: function (data) {
                         //this gets called when server returns an OK response
                         alert("it worked!");
                    },
                    error: function (data) {
                         alert("it didnt work");
                    }
                });
            });           
        }

In my index template, I have created a button which calls the returnJsonTop() function when it is pressed:

<button id="submitJson" onclick="returnJsonTop();">Deploy</button>

Currently, when I press the Deploy button, I just get the 'it didn't work' alert that has been setup to handle an errors. I'd really appreciate someone pointing me in the right direction here. I suspect the issue is in my urls.py files but I've tried various combinations of urls without any luck.

3 Answers 3

1

You're trying to access body on request.POST. But body is an attribute directly of the request. Your code should be:

    request_data = request.body
    print("Raw Data: " + request_data)

Also note, in your Javascript that $(document).ready line makes no sense there; you should remove it.

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

Comments

0

For those reading this later, this is what I did:

mainapp/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')),
    url(r'^admin/', admin.site.urls),
]

NetworkTopology/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^json/$', views.returnjson, name='returnjson'),
]

NetworkTopology/views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return render_to_response('index.html')


@csrf_exempt
def returnjson(request):
    if request.is_ajax():
        request_data = request.POST
        print("Raw Data: " + str(request_data))
        return HttpResponse("OK")

I was getting a 403 error so I added '@csrf_exempt'. I'll probably change this to handle it properly afterwards.

Return JSON function:

function returnJsonTop(){
            $.ajax({
                method: 'POST',
                url: '/NetworkTopology/json/',
                dataType: 'json',
                data: JSON.stringify(nodes.get(),null,4)
            });         
    }

Comments

0

First of all you dont even need to use all this in your ajax call

  data: JSON.stringify(nodes.get(),null,4),

replace by

  data: nodes.get(),

should be enough as long as this method returns a valid json object

Second one, I ´d strongly recommend you to use a framework to help you to parse JSON

Python have may, but to illustrate this example, I've used django rest framework, which is a very good one.

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import json
import controllers#this class belongs to my business logic layer, you can encapsulate yours and use instead of it

#in this solution you must create a pre-parser to handle responses
class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt # this is for prevent invasions
def login(request):
#this one here handle your jquery post data into a valid json object in python represented by a Dict
    envelopin = json.loads(request.body)
# here we pass the dict inside my business controll logic routine which also responds with a valid Python Dict
    envelopout = controllers.login(envelopin)
# and for last, we use our pre-parser Class to make your response be handled by jquery as valid json
    return JSONResponse(envelopout)

and that is it, you success jQuery data variable, will hold the envelopout json object, in the same shape as it has inside yor django-python code.

hope this help

Comments

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.