[Answer]-Issue with my Django request from a JSON POST

1đź‘Ť

Looks like its happens because of python namespace rules. If you define variable in function:

>>>def random_func(input):
       t = input
       return t
>>>t
Traceback (most recent call last): File "<input>", line 1, in <module> 
NameError: name 't' is not defined

Its won’t be global variable.
So, what you need to do is too ways:
first, put code with base manipulation in function save_events_json:

def save_events_json(request):
    t = request.raw_post_data
    con = Connection("mongodb://xxx.xxx.xxx.xxx/")
    db = con.central
    collection = db.brief
    test = {"name":"robert","age":"18"}
    post_id = collection.insert(t)
    from django.http import HttpResponse
    return HttpResponse(content=t)

or set the variable “t” global:

def save_events_json(request):
    global t
    t = request.raw_post_data
    return t 

0đź‘Ť

Dear @Kyrylo Perevozchikov, I’ve updated my code :

import pymongo
from pymongo import Connection
from django.utils import simplejson as json
from django.http import HttpResponse,HttpRequest
request = HttpRequest()
if request.method == 'POST':
    def index(request):
        global t
        t = request.raw_post_data                          
  post_id=Connection("mongodb://xxx.xxx.xxx.xxx/").central.brief.insert(t)
        return HttpResponse(content=t)
else:
    def index(req):
        s="Not A POST Request"
        return s

When I click on the jquery button I have the “Not A POST Request”

👤Manuhoz

Leave a comment