How to access Backbone Fetch data server side - javascript

I have a backbone model that I am calling fetch with. I have a flask server on which i need to access the id of the backbone model. I cannot seem to get my hands on the id of the model on the server. How can I access the entityId in my flask code
BB.Politician = Backbone.Model.extend({
defaults: {
type: "Politician"
},
url: "/my_url_here"
});
var currentUser = new BB.Politician({"entityId": "1625"});
currentUser.fetch({
//method: "POST",
success: function(user){
currentUserView.render();
}
});
#Flask server code
#app.route('/my_url_here', methods=['GET', 'POST'])
def return_poitician():
print request
print request.args
print request.values
#none of the above print statements are giving me the "entityId"
return data
I also tried adding in the id in the route but that just threw a 404 error when the fetch() executed:
#app.route('/my_url_here/<entityId>', methods=['GET', 'POST'])
def return_poitician(entityId):
print entityId

#app.route('/my_url_here/<entityId>', methods=['GET', 'POST'])
isn't picking up any id because you aren't sending any.
Backbone fetch uses the id field of the model to construct the fetch URL, in your case I would recommend turning the entityId into id:
BB.Politician = Backbone.Model.extend({
defaults: {
type: "Politician"
},
url: "/my_url_here"
});
var currentUser = new BB.Politician({"id": "1625"});
and let Backbone construct the GET, which would look like:
"/my_url_here/" + this.get('id'); // this refers to model
which turns into
"/my_url_here/1625"
Backbone.Model.url also accepts function as value so you can define your own logic for constructing URLs. For instance, if you must retain the entityId you can construct your url like:
url: function () {
return "/my_url_here" + this.get('entityId');
}

Related

Not able to retrieve data values from Ajax GET call into Django view

I am trying to query the employee list based on parameter I send
through ajax call inside data, but it giving me an error (i want it
through GET req only )
Js ajax func
$(document).ready(function () {
$(".call_ajax").click(function () {
$.ajax({
url: "/employee_list",
type: "GET",
contentType: "application/json",
dataType: "json",
data: {
designation: "soft eng",
},
headers: {
"X-CSRFToken": csrftoken,
Authorization: my_token,
},
success: function (data) {
console.log(data);
},
error: function (xhr) {
//Do Something to handle error
console.log(xhr.error);
},
});
});
my view
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.data['designation']
print(data_)
employees = Employee.objects.all()
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
error i am getting in browser
GET http://127.0.0.1:8000/employee_list/ 500 (Internal Server Error)
error in Django log
File "C:\Users\atif\PycharmProjects\CodePlatform\syntax_fight\api_\views.py", line 42, in employee_list
data_ = request.data['designation']
KeyError: 'designation'
request.data returns the parsed content of the request body.
This is similar to the standard request.POST and request.FILES
You can use request.GET.get('designation')
#csrf_exempt
#api_view(['GET', 'POST', 'PUT', 'DELETE'])
#permission_classes([IsAuthenticated])
#authentication_classes([TokenAuthentication])
def employee_list(request):
if request.method == 'GET':
data_ = request.GET.get('designation') # Here I made changes
print(data_)
employees = Employee.objects.filter(designation=data_) # Map parsed data with database field
students = Student.objects.all()
user = MyUser.objects.all()
serializer = EmployeeSerializer(employees, many=True)
serialized_sudents = StudentSerializer(students, many=True)
multi = {
'employees': serializer.data,
'students': serialized_sudents.data
}
# serializer2 = UserSerializer(user, many=True)
return JsonResponse(multi, safe=False)
or
You can override get_queryset method. As for query string parameters request.data holds POST data, you can get query string params through request.query_params
def get_queryset(self):
data = self.request.query_params.get('designation')
queryset = Model.objects.filter() # use whatever you want filter
return queryset
To know more about request.data and request.query_params, here is the link
Request parsing link
It is most probably because you are using GET, but the data resides in body. Have a look at this. To try to fix this, change your request method to POST:
$.ajax({
url: "/employee_list",
type: "POST",
...

How to make a POST request using jquery and access POST data in a django view (not generic views), without using csrf token?

I have dictionary in javascript something like this:
var data = {"name":"nitin raturi"}
Now I want this data to be accessed in my django view something like this:
def my_view(request):
data = request.POST
How to send data to my url using jquery?
lets do this.
This is your dictionary in javascript:
var data = {"name":"nitin raturi"};
Now define a function that will make a post request using jquery.
function send_data(data, callback) {
// callback is a function that you should pass to handle your response
$.ajax({
type: "POST",
url: '/sample-url/', // change this to your url here
data: {"data": JSON.stringify(data)},
success: function (response) {
callback(response);
},
});
}
Now use the send_data function like this:
send_data(data,function(response){
//handle your response here
console.log(response);
})
Now you can access your data in your django view like this:
import json
#csrf_exempt
def my_view(request):
data = request.POST.get('data')
data = json.loads(data) # this will convert your json data to python dictionary
name = data.get("name")
// Handle your data and return anything you wish
return render(request,"index.html",{})

Problem sending information between Django template and views using AJAX call

I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page.
With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix.
This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert.
var arr = { City: 'Moscow', Age: 25 };
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = norm_data.toString();
alert( norm_data );
}
});
This is my Django URLs code to receive the request:
path('applications/1/normalize', views.normalize, name="normalize")
This is the python view to retrieve the code and send it back to the javascript file:
from django.http import JsonResponse
def normalize(request,*argv,**kwargs):
norm_data = request.POST.get(*argv, 'true')
return JsonResponse(norm_data, safe = False)
You need to parse your Object to an actual json string. The .toString() will only print out the implementation of an objects toString() method, which is its string representation. By default an object does not print out its json format by just calling toString(). You might be looking for JSON.stringify(obj)
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = JSON.stringify(norm_data);
alert( norm_data );
}});
I've observed that there's a difference between POST data being sent by a form and POST data being sent by this AJAX request. The data being sent through a form would be form-encoded whereas you are sending raw JSON data. Using request.body would solve the issue
from django.http import JsonResponse
def normalize(request):
data = request.body.decode('utf-8')
#data now is a string with all the the JSON data.
#data is like this now "arr%5BCity%5D=Moscow&arr%5BAge%5D=25"
data = data.split("&")
data = {item.split("%5D")[0].split("%5B")[1] : item.split("=")[1] for item in data}
#data is like this now "{'City': 'Moscow', 'Age': '25'}"
return JsonResponse(data, safe= False)

How to make POST requests to class-based Views in Django

I have created different class-based views on Django. On the HTML i created some forms make a request with AJAX. My problem is that it gives me
Method Not Allowed (POST)
I don know if i'm doing it rigth, or if i need to modify something for it to work.
My view.py is something like this
class Landing(View):
def get(self,request):
if request.method == 'POST':
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
return render(request,'landing.html',{'foo':'bar'})
And i send the reques from Javascript
$(document).ready(function() {
$('#productos').on('change', function(e) {
//Call the POST
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var value = $('#productos').val();
$.ajax({
url: window.location.href,
type: "POST",
data: {
csrfmiddlewaretoken : csrftoken,
value : value
},
success : function(json) {
console.log(json);
drop(json);
},
error : function(xhr,errmsg,err){
console.log(xhr.status+": "+xhr.responseText)
}
});
});
});
I got some of the code from a web, but i really don't know how to use it, since they used it without class-based views.
So, What does need my code to accept the POST method?
The dispatch method of a class based view determines which function is called, so far you've written a get function, but no post function so just move the logic into a post function.
class Landing(View):
def post(self,request):
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
def get(self, request):
return render(request,'landing.html',{'foo':'bar'})

Django, passing JSON to frontend, 'str' doesn't have 'iteritems'

I'm creating json data this way:
def get_all_from_database():
urls = Url.objects.all()
ips = Ip.objects.all()
urls_json = serializers.serialize('json', urls)
ips_json = serializers.serialize('json', ips)
return urls_json, ips_json
and I try to pass it to frontend using ajax:
#csrf_exempt
def send_results(request):
if request.is_ajax():
address = request.POST.get('url')
urls, ips = get_all_from_database()
return HttpResponse(urls, ips)
js code:
$.ajax({
type: "POST",
url: "/link_finder/send_results/",
data: {
url : web_page,
},
success: function(data) {
alert(data);
},
error: function(xhr, textStatus, errorThrown) {
alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
}
And I get this error:
INTERNAL SERVER ERROR500AttributeError at /link_finder/send_results/
'str' object has no attribute 'iteritems'
Why? And what should I change?
HttpResponse takes only one body argument, you are passing in two.
Don't create two JSON strings, build one, using a custom serializer to handle multiple querysets:
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.core import serializers
from django.db.models.query import QuerySet
def get_all_from_database():
urls = Url.objects.all()
ips = Ip.objects.all()
return urls, ips
class HandleQuerySets(DjangoJSONEncoder):
""" JSONEncoder extension: handle querysets """
def default(self, obj):
if isinstance(obj, QuerySet):
return serializers.serialize("python", obj, ensure_ascii=False)
return super(HandleQuerySets, self).default(obj)
#csrf_exempt
def send_results(request):
if request.is_ajax():
address = request.POST.get('url')
urls, ips = get_all_from_database()
data = HandleQuerySets().encode({'urls': urls, 'ips': ips})
return HttpResponse(data, content_type='application/json')
I've also set the correct Content-Type header for you.

Categories

Resources