Get query list parameter from Datatable in Django - django

I'm using DataTable with django and I'm trying to set up the serverSide option. Everything is working fine except the order parameter. Datatable is sending all the parameters to the backend in which the order comes like this:
order[0][column]: 0
order[0][dir]: asc
order[1][column]: 2
order[1][dir]: desc
I'm trying to get all the order parameters in a list with the getlist() function but I'm getting everytime an empty list
orders = request.GET.getlist('order[]')
What am I missing?

Ok, I found the solution. I was sending the ajax as a form-encoded and it was getting the keys for order as a literal string order[0][column] order[0][dir]. What I had to do is send the ajax in datatable as a JSON and get the parameters with json.loads() in the view:
DataTable
"ajax": {
"url": url,
"contentType": "application/json",
"type": "POST",
"data": function (d) {
return JSON.stringify(d);
}
},
View
request_data = json.loads(request.body)
dt_draw = request_data.get('draw')
dt_start = request_data.get('start')
dt_length = request_data.get('length')
dt_search = request_data.get('search').get('value')
dt_order = request_data.get('order')

Typicall you get an empty list for getlist if the keyword you are looking for does not exist. Try request.GET.getlist('order') instead.

Related

Django get wrong value from json.loads in POST request

I need to pass a user-input geojson with request to further process the information. The data comes from a textfile and then passed to the views.py in django with a POST request. Before passing to the view I checked the value of the string and that appears to be correct. After passing that to the view, I made a print check and some values inside the JSON are changed in string like:
"{"id": "13871", "type":SOH# "Feature", "properties": {"lanes": 0, "highway": "pedestrian" etc....."
or
"{"id":"86","type":"FeatureSOHVT","properties":etc......."
The bold strings sometimes appear even inside the values of the dictionary.
The js file:
$.ajax({
type: 'POST',
url: $('#confImp').data('url'),
dataType: 'json',
data: {'streetWeb': JSON.stringify(street_web), 'int_points': JSON.stringify(int_points_loaded), 'csrfmiddlewaretoken': csrftoken,},
success: function(res){blablabla}
The django views.py:
elif 'streetWeb' in request.POST:
print(json.loads(request.POST.get('streetWeb')))
request.session['Working_area_final'] = json.loads(request.POST.get('streetWeb'))
print(json.loads(request.POST.get('int_points')))
request.session['int_points'] = json.loads(request.POST.get('int_points'))
return JsonResponse({'Risposta': 'Done'})

Django checkbox data navigation [duplicate]

I'm sending the following JSON to my webservice:
{
"message": "Hello!",
"people": ["Aaron", "Randy", "Chris", "Andrew"]
}
And when I access the QueryDict, dict['people'] returns the last item in the list, Andrew, not the list. What am I doing wrong?
When inspecting the object:
Use the getlist() method:
people = request.GET.getlist('people')

Validate response in Postman test script

I am inserting data in postman. I want to apply validation from post method in test script. I am new to postman, I am not able to understand.
Here is the JSON.
{
"firstname": "pradeep",
"lastname": "tiwari",
"mobile_no": 9911844349,
"email": "pradeep#gmail.com",
"user_type": 4,
"password": "pradeep1",
"confirmPassword":"pradeep1",
"dob":"nanana",
"u_org":25,
"isfoundingpartner":"undifine",
"gender":1
}
You can use built in snippets for starters to validate your basic response messages. https://learning.getpostman.com/docs/postman/scripts/test_examples/
In order to carry out validation on your responses, you will first need to parse the data into a JavaScript object using below
var jsonData = pm.response.json();
You can use the below code to check for particular values in the response body
pm.test("Verify Json values", function () {
pm.expect(jsonData.firstname).is.to.equal("pradeep");
pm.expect(jsonData.lastname).is.to.equal("tiwari");
pm.expect(jsonData.gender).is.to.equal(1); `
});

Postman - Use part of the response data from one test in another test

I require help to execute a postman test which requires a response output from another test. I have checked with various forums but a solution is not available for this particular scenario.
Example
Test 1 response:
{
"items": [
{
"email": "archer+qa01#gmail.com",
"DocumentName": "tc",
"type": "URL",
"url": "https://localhost:8443/user/terms?statusno=a5f2-eq2wd3ee45rrr"
}
]
}
Test 2:
I need to use only the a5f2-eq2wd3ee45rrr part of the response data from Test 1, this can be seen in the url value above. I need to use this value within Test 2
How can I make this work with Postman?
Not completely sure what the response data format is from the question but if it's a simple object with just the url property, you could use something simple like this:
var str = pm.response.json().url
pm.environment.set('value', str.split('=', 2)[1])
This will then set the value you need to a variable, for you to use in the next request using with the {{value}} syntax in a POST request body or by using pm.environment.get('value') in one of the test scripts.
Edit:
If the url property is in an array, you could loop through these and extract the value that way. This would set the variable but if you have more than 1 url property in the array it would set the last one it found.
_.each(pm.response.json(), (arrItem) => {
pm.environment.set('value', arrItem[0].url.split('=', 2)[1])
})
If you get JSON response and then send JSON in body, I would do the following:
1) In test script(javascript):
var JsonBody = pm.response.json();
var strToParse = JsonBody.url;
var value = strToParse.slice(indexOf("?status=")+"?status=".length);//parse string
//manually but you can google for a better solutions.
pm.environment.get("varName" , value)
2) You can use it! In scripts like: pm.environment.get("varName"), and everywhere else using {{varName}}

Send Json via $.load() of jQuery in a GET request to Django

Happy coding weekend to everyone!!!.
I'm stuck trying to send a JSON object via $.load() of jQuery, i want to send it with the GET method, this is the code that i have in my javascript code, I attached the Ajax request that receives the JSON Object for clarity:
function ajaxLoadClasses() {
$.ajax({
url: 'load_classes/',
type: 'GET',
dataType: 'json',
success: function(json) {
$.each(json, function(iterator,item) {
loadViaGet(item);
});
},
error: function(xhr, status) {
alert('Sorry, there was a problem!');
},
complete: function(xhr, status) {},
});
}
function loadViaGet(item) {
$div = $('div.myClass');
//Here is where I'm stuck, I'm not sure if this is the way to send the JSON obj
$div.load('thisAppURL/?json=' + encodeURIComponent(item), function() {
alert('Load was performed');
});
}
The "item" json obj received was made out of a Model of Django using
jsonToSendToAjax = serializers.serialize('json', obj)
And I don't think that I'm using the correct methods in my Django to deserialize the JSON object or to convert the JSON object into a Python object so I can handle it in my view and send it to a template:
def popUpForm(request):
jsonData = request.GET['json']
deser = serializers.deserialize('json', jsonData)
#This could be another way to convert the JSON object to a Python Object
#pythonObj = simplejson.loads(jsonData)
return render_to_response('class_pop_up_form.html', deser)
It will be very helpful if someone can help me with this!! I'm really struggling with it but I don't find the right way to do it.
EDIT 1 :
I want to send the JSON object via the GET with the $.load() function, not with the POST method,as I read in the jQuery api: http://api.jquery.com/load/ the $.load() method works as follow: .load( url, [data], [complete(responseText, textStatus, XMLHttpRequest)] )
The POST method is used if data is provided as an object; otherwise, GET is assumed.
EDIT 2:
Forget about sending the json object via the GET method, now I'm using the POST method, but now I don't figure out how to use that json object in my Django View.py, don't know if i need to deserialize it or not, the format of the json object that I'm using is the following:
{"pk": 1,
"model": "skedified.class",
"fields": {
"hr_three": null,
"group": 1,
"name": "Abastecimiento de agua",
"day_three": null,
"day_one": "1 , 3",
"hr_one": "10+/3",
"online_class": null,
"teacher_name": "Enrique C\\u00e1zares Rivera / ",
"day_two": null,
"class_key": "CV3009",
"hr_two": null }
}
This isn't how jQuery suggests you should send the data and it's probably not a good idea to do it this way either. Your url gets very ugly and long very quick if you add the json string to it like that.
Use the second argument for $.load; "data" (see http://api.jquery.com/load/) instead. So something like
$div.load('thisAppURL', {"json": encodeURIComponent(item)});
Also, if you want to trace the output, I'd sugest using the third argument, the callback function, and use console instead of alert. You can get the actual return from the server that way too. So you'd get something like:
$div.load(
'thisAppURL',
{"json": encodeURIComponent(item)},
function(response, status, xhr){
console.log(response);
}
);
the question was not clear to me but you can send json via load as the second argument
$div = $('div.myClass');
//Here is where I'm stuck, I'm not sure if this is the way to send the JSON obj
$div.load('thisAppURL/?json=' + encodeURIComponent(item),{"name":"john","age":"20"}, function() {
alert('Load was performed');
});
for converting javascript array to json see this answer Convert array to JSON
and for deserializing json in django Django Deserialization