So I'm using request from https://github.com/request/request#forms. In tsx file, I'm passing
id: id, text: string, array: number[].
post(
{json: true, url: '...', form: {id: id, text: text, array: array}},
(error, response, body) => {
if (response.statusCode === 400) {
dispatch(errStep(body['text']));
} else {
dispatch(addStep(body));
}
}
)
This is a post method with the body {id: id, text: text, array: array}. However, from Django, when I print the request.data, I receive <QueryDict: {'text': ['hello'], 'id': ['12'], 'array[0]': ['51'], 'array[1]': ['52']}>.
This way, I can't retrieve the array ['51', '52] by calling request.data.getlist('array').
I would like my request.data to be in this format: <QueryDict: {'text': ['hello'], 'id': ['12'], 'array': ['51', '52']}> because [51, 52] is returned by calling request.data.getlist('array').
Thanks!
qsStringifyOptions: {arrayFormat: 'repeat'} as one of the options in post call will transform 'array[0]': ['51'] , 'array[1]': ['53'] to 'array': ['51', '52']
Related
I am using Django and Ajax.
Im my view I have:
class MainView(View):
def get(self, request):
if not request.is_ajax():
return render(request, "main.html")
# hard coded both options for testing
return JsonResponse({"data": "xyz"}, status=400)
# return JsonResponse({"data": "xyz"}, status=200)
my ajax function looks like:
$("#start_calculation_button").click(function () {
$.ajax({
url: "/",
type: 'get',
data: {
...
},
success: function (response) {
console.log(response.data);
},
error: function (response) {
console.log(response.data);
}
})
})
But only the success function works? While the error part just gives back undefined
Any idea's why it is that way?
How can I fix it?
The parameters of success and error are different, in case of a success, these parameters are result, status, and xhr whereas for error, the parameters are xhr, status, and error. You thus should parse the xhr data with:
$("#start_calculation_button").click(function () {
$.ajax({
// ⋮
success: function (response) {
console.log(response.data);
},
error: function(xhr) {
var err = JSON.parse(xhr.responseText);
console.log(err.data);
}
})
})
I want to show the dropdown list with data response via Ajax call. Everything is working fine but I am getting this ValueError: Cannot use None as a query value error.
view:
def load_brand(request):
if request.is_ajax():
term = request.GET.get('term')
brand = Brand.objects.all().filter(brand__icontains=term)
return JsonResponse(list(brand.values()), safe=False)
ajax:
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {id: item.id, text: item.brand};
})
};
}
},
minimumInputLength: 1
});
In your ajax call you have not send the data i.e : which user type inside select2 and you are accessing them i.e : request.GET.get('term') which is empty so your .filter(brand__icontains=term) giving you error because term value is null.
Instead you can add below as well in your ajax call :
$('#id_brand').select2({
ajax: {
url: '/brand/ajax/load-brand/',
dataType: 'json',
data: function(params) {
var query = {
term: params.term, //this will be paass
type: 'public' //optional..
}
// Query parameters will be ?term=[values]&type=public
return query;
},
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
id: item.id,
text: item.brand
};
})
};
}
},
minimumInputLength: 1
});
Also , at your server end you can check if the term has any value i.e :
if term:
brand = Brand.objects.all().filter(brand__icontains=term)
For more information check this
I am trying to pass data to the template in Json format. JsonResponse returns an error
TypeError: Object of type method is not JSON serializable
Here is the code view that causes the error:
if request.method == 'POST':
... SOME CODE HERE ....
elif request.method == 'GET' and request.is_ajax():
df = pd.read_csv(project.base_file, encoding='ISO-8859-1')
cols = df.keys
return JsonResponse({'features': cols, }, status=200)
else:
form = mForm(project_id=pk)
The Json Data should be processed in the following Ajax Code:
$(document).ready(function(){
var id_number =$("#projectID").text();
$("#btnSelect").click(function(){
$.ajax({
url: '',
method: 'GET',
data: {
project_id: id_number,
},
success: function(response){
$("#id_features").text(response.features)
}
});
});
});
The problem is here:
df = pd.read_csv(project.base_file, encoding='ISO-8859-1')
cols = df.keys
^
because keys is a method and you can't serialize a method into JSON(that's the error title right?) and since you want df value as serialized JSON, you must call that method to achieve it
but try
cols=df.keys()
I run into a problem when use Ember-data to save a model. The JSON structure for my model looks like:
{ post: {
id: 1,
name: 'post-1',
trigger: ['trigger-1', 'trigger-2'],
data: ['data-1', 'data-2']
}
}
Because 'data' and 'trigger' are reserved keywords for DS.Model, I created a mapping and renamed them to sc_data and sc_trigger as suggestion by Jurre using
Application.SERIALIZATION_KEY_MAPPINGS = {
'sc_data': 'data',
'sc_trigger': 'trigger'
};
Application.ApplicationSerializer = DS.ActiveModelSerializer.extend({
keyForAttribute: function (attr) {
if (Application.SERIALIZATION_KEY_MAPPINGS.hasOwnProperty(attr)) {
return Application.SERIALIZATION_KEY_MAPPINGS[attr];
} else {
return this._super(attr);
}
}
});
So my model for post looks like:
Application.Post = DS.Model.extend({
name: DS.attr('string'),
sc_trigger: DS.attr(),
sc_data: DS.attr()
});
the sc_trigger and sc_data are renmaed mapping for data and trigger.
It all worked fine when use this.store.find('post') and this.store.find('post', 1), i.e. GET calls. When I try to create a record using this.store.createRecord('post'), it creates a record with the correct attribute name sc_data and sc_trigger.
var newPost = this.store.create('post', {
name: 'test post',
sc_data: [],
sc_trigger: []
})
And the serialize function interprets the mapping correctly as well. newPost.serialize() returns
{
name: 'test post',
data: [],
trigger: []
}
But when I call newPost.save(), in the HTTP request body of the POST call, data and trigger field is missing. It only has
{
name: 'test post'
}
I have no idea why newPost.save() doesn't generate the correct request body when serialize() is working just fine.
Update
I managed to get around this by removing the keyForAttribute mapping and using
Application.ApplicationSerializer = DS.ActiveModelSerializer.extend({
attrs: {
sc_data: {key: 'data'},
sc_trigger: {key: 'trigger'}
}
});
This seems to be the suggested way to handle data with reserved keywords.
Which ember data version and emberjs version are you using?
Try saving with id like-
var newPost = this.store.create('post', {
id:1
name: 'test post',
sc_data: [],
sc_trigger: []
});
Save and create always expects id. So it's better to save/create record with id.
to have autocompletion on an input,I do this:
in views.py:
def getpositions(request):
if request.is_ajax():
query = request.GET.get("term", "")
positions=Position.objects.filter(name__icontains=query)
results = []
for position in positions:
position_json={}
position_json['name']=position.name
results.append(position_json)
data=simplejson.dumps(results)
else:
data = 'error'
return HttpResponse(data, mimetype='application/json')
in template:
$(document).ready(function(){
$("#positions").autocomplete({
source: "{% url CompanyHub.views.getPositions%}",
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.name,
value: item.name
}
}));
},
minLength: 2,
});
});
and #positions is : <input type="text" id="positions" />
every thing is ok,but it just show Undefined instead of showing list of results,I tryed many things but no way!!
jQuery UI autocomplete doesnt have a success option you are using to format your data. Check the option list here http://jqueryui.com/demos/autocomplete/ . Instead You can use a callback function for source option and handle your own ajax call yourself and format data like you want.
$("#positions").autocomplete({
source: function( req,resp ) {
$.get("{% url CompanyHub.views.getPositions%}",
{term:req.term},function(data){
resp( $.map( data, function( item ) {
return {
label: item.name,
value: item.name
};
})
);
});
},
minLength: 2,
});