4👍
✅
Javascript
function AddPropety(){
var list = [{'name':'parrot','color':'green'},{'name':'dog','color':'brown'},etc...];
var formData = new FormData($('#submit_form')[0]);
formData.append("list", JSON.stringify(list));
$.ajax({
url: "{% url 'add_details' %}",
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
});// end of $.ajax
return false;
}
ajax.py
def add_details(request):
response_data = {}
if request.is_ajax():
lists = request.POST.get('list')
jd = json.dumps(lists)
list = eval(json.loads(jd))
print lists
for list in lists:
print list
response_data['status'] = "success"
else:
response_data['status'] = "Error"
return HttpResponse(json.dumps(response_data), content_type='application/json')
5👍
var arr = ["a","b",,,"e"];
var json_string = JSON.stringify(arr);
.
json_string = '[{'name':'parrot','color':'green'},{'name':'dog','color':'brown'},etc...]' # passed from JavaScrip try:
import simplejson as json
result = json.loads(json_string)
- [Django]-What do I need to run Sentry inside my django site
- [Django]-Can't build index for solr/haystack: unknown field 'django_id'
- [Django]-Django.db.utils.InterfaceError: (0, '')
- [Django]-Django crispy-forms dynamic label_class and field_class
- [Django]-Passing context from child to parent template in Django
- [Django]-NameError: name PositiveSmallIntegerField is not defined
- [Django]-Keep User and Group in same section in Django admin panel
0👍
In js you have to stringify your array:
let arr = [{"foo1": bar1}, {"foo2": bar2}]
let data = {"data": JSON.stringify(arr)}
$.ajax({
url: url,
method: 'POST',
headers: {"X-CSRFToken": variables.csrfToken},
data,
})
In views.py you may overide create method if using generic views:
import json
from rest_framework.generics import CreateAPIView
class MyCreateAPIView(CreateAPIView):
serializer_class = MySerializer
def create(self, request, *args, **kwargs):
"""
checks if post request data exists initializes serializer with many=True
else executes default CreateModelMixin.create method
"""
json_string_data = request.data.get('data', False)
if not json_string_data:
return super(MyCreateAPIView, self).create(request, *args, **kwargs)
else:
json_data = json.loads(json_string_data)
serializer = self.get_serializer(data=json_data, many=True)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
- [Django]-How to download data from azure-storage using get_blob_to_stream
- [Django]-Django admin login returns Forbidden 403 CSRF verification failed. Request aborted
Source:stackexchange.com