I have this following view which I get data from a model and thereafter serialize it into JSON.
views.py
def polling(request):
if request.is_ajax():
data = UserReview.objects.filter(movie_id=request.GET['m_id'])
serializers.serialize('json', data)
return HttpResponse(data, mimetype='application/json')
else:
raise Http404
At the client side I want to show this content now. I'm using jQuery's function getJSON to archive this. It won't show anything, and the setTimeout doesn't work as well. But I get a response when I debug it with firebug, it however doesn't call the alert() function to view the data. I've been trying to figure out what the problem could be for some time now. So I wonder if there's something wrong with my script?
javascript
function polling() {
$.getJSON( "/polling/",
{m_id: {{movie_info.id}} },
function(data) {
alert(data)
setTimeout(polling, 5000)
});
};
Some general methods that will help you find out what is wrong.
Use console.log very liberally on the front end to make sure everything is going as planned
http://api.jquery.com/jQuery.ajax/ Callback functions as suggested in a comment, make sure you at least logg an error
https://docs.djangoproject.com/en/dev/topics/logging/ set up a debug logger, make sure that you can see what is going on and what django is actually returning as json.
http://docs.python.org/library/pdb.html Better yet drop this badboy anywhere in your code and MAKE SURE that everything is going the right way. If your success is not being called ont the front end i bet the error is in django! find out where.
You can view the errors in the HTML tab in firebug if debug=True or you can just request /polling/ through your browser and view the django error screen.
using some or any of these should put you in a fine place to solve your problem django dev server makes it an absolute ease to breeze through these errors please do some research and find out the many many debug tools made available to you!
I'm new to all of this but have you tried to use.
$.ajax
({
url: "/Build/AllStatuses",
dataType: 'json',
success: function (buildstatuses)
This is how I used to call my json and it seems to work.
Related
I am currently in the middle of doing a Laravel tutorial on Youtube and I've been catching on pretty quickly but I hit a snag and I have absolutely no idea what the problem is. I'm trying to route to a view and I am receiving an error saying that the page does not exist. Here is what I got (forgive me if my terminology is lacking):
The web.php file in the routes folder is configured for 'companies' to go to the 'CompaniesController':
Route::resource('companies', 'CompaniesController');
The create function located in the CompaniesController only purpose is to return the view 'companies.create' located in the appropriate place, 'resources/views/companies/create.blade.php'
public function create()
{
//
return view('companies.create');
}
If more information is needed let me know but this should be pretty straight forward. Other functions in the controller work fine, its only the one that is the most simple that isn't working.
Appreciate any help I get.
If your http request is GET:
Route::get('/companies', 'CompaniesController#create')
Else if request is POST:
Route::post('/companies', 'CompaniesController#create')
create would respond to a POST request by default, e.g., the endpoint of a creation form. It sounds like you're trying to display a simple view with a GET.
See https://laravel.com/docs/5.5/controllers#resource-controllers
I'm still a bit new to Ember. I'm using Ember 1.13 with Ember Data and the DS.RESTAdapter. For debugging purposes, as well as educational (such as getting a feel for how Ember Data works with various options such as the shouldReload* functions), I want to log every API request with mainly the URL called and optionally how it was called (eg, from a store.findAll() or store.queryRecord(), etc.). Is there a single place (my guess is somewhere in adapter:application?) where I can put a single console.log('URL called: ', url, ', from: ', callingFunction); that handles all of this?
If you use the JSONAPIAdapter or the RESTAdapter just override ajax() on the adapter to log the URI:
ajax(url, type, options) {
console.log(url);
return this._super(...arguments);
}
There is no easy way to get the caller function. Analyse the callstack, if its just for debugging purposes!
But, maybe just use the Browser log XMLHttpRequest option if its for debugging?!
If you want to know how it works, checkout the code. The adapter and the store is where you can look for knowledge.
I am working on an application with some friends and the back end REST API is in django. I sometimes get huge blocks of html printed to the console in place of anything meaningful, when I call an API from my angular front end. I have done some googling and I can't seem to find an answer of how to turn this off and make django return just error strings or json or something instead. Can someone help me get rid of this html?
Try using: https://docs.djangoproject.com/en/1.7/topics/logging/#configuring-logging
This will let you configure the logging in your django project.
Your Django app is working in debug mode. Please try this.
Go to ../yourdjangoproject/yourdjangoproject/settings.py
and find line Debug = True. Making it Debug=False will stop it from spitting out huge html upon errors.
Another thing you can do to only see errors as nice api response strings is this:
Find the view function which is giving the error, which can be found through the same huge html error message or by checking the view for url in urls.py
Then surround the whole view in try except like this.
def your_api_view(bla):
try:
#all of the view code goes here
except Exception as e:
return Response({"Error":e})
This way the error message will be shown to you like normal api response string.
I am making a post via Jquery ajax that looks like this:
$.ajax({
type: 'POST',
url: "/sandbox/read_demands/",
data: {
"partner_ref": "PH",
"return_field": ["summary", "details"]
},
success: [read_demands_response],
dataType: 'json'
});
I then recieve the data on the server-side with a simple Django view that only prints request.POST into a log. The data then looks like this:
{u'return_field[]': [u'summary', u'details'], u'partner_ref': [u'PH']}
As you can see, the key 'return_field' has become 'return_field[]' and the value for 'partner_ref' is now a list. What on earth is going on? Am I missing something complected obvious in the jquery post that causes my data to be malformed or is do you think this error comes from somewhere else? I am trying to rule-out different possibilities until I can find the cause of the problem.
This is jquery 1.8.2 and Django 1.4 btw.
The first one is just jQuery being jQuery. For reasons best known to themselves, the makers of jQuery believe that PHP is the only way to write server-side applications, and PHP expects fields that have more than one value to have the [] suffix - so if you don't provide one, it'll add it. You just have to use it like that in Django.
However, the second one is not an error. It's just how a Django QueryDict works: any value can have multiple items, so they'll always be represented as a list. However, request.POST['partner_ref'] will correctly give the single value. And in fact to access both values of the other key, you'll need to do request.POST.getlist('return_field[]').
Edit: as pointed out in the comments, $.ajaxSettings.traditional = true; fixes the jQuery issue.
I've been dealing with the same problem, and found this related question.
How to get an array in Django posted via Ajax
The answer recommends using
request.GET.getlist('data')
I'm trying to POST some JSON and a binary file from an iPhone to a Django server running django-piston using ASIHTTPRequest
I know how to get it to work if I am ONLY sending JSON strings, and I know how to make it work if I am ONLY sending a file, but doing both is tricky.
So we'll start with ASIHTTPRequest code
ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:url];
[request setRequestMethod:#"POST"];
[request setPostFormat:ASIMultipartFormDataPostFormat];
[request appendPostData:[#"{\"save\":{\"name\":\"iostest\"}}" dataUsingEncoding:NSUTF8StringEncoding]];
[request addData:UIImageJPEGRepresentation([UIImage imageNamed:#"test.jpg"], 1.0f)
withFileName:#"test.jpg"
andContentType:#"image/jpeg"
forKey:#"data"];
[request setDelegate:self];
[request startAsynchronous];
My best idea here is that adding raw string data directly to the POST body and then adding a file just doesn't work.
But if I instead try
[request setPostValue:#"{\"name\":\"iostest\"}" forKey:#"save"];
Then the piston data dictionary will store ['save'] as a string instead of a deserialized object, so it will literally deliver the string
"{\"name\":\"iostest\"}"
Here's my Piston handler code
def create(self, request):
data = request.data
print(data['save']) #{\"name\":\"iostest\"}"
print("Files: " + request.FILES['data'].name) #test.jpg
print("Data Save Name: " + data['save']['name']) #crash, interprets this as a string indeces lookup
Ideas are welcome.
I have basically hacked my way around this.
The basic problem is that the request format in which Django expects files to be submitted to the server is one which django-piston literally just drops the ball on.
When it encounters multipart requests, it simply doesn't try to parse the data.
The solution to this problem is to manually call the parsing engine, which, in the case of JSON, is straight out of django.utils (which is kind of disappointing).
You achieve this by using ASIHTTPRequest (or the request module of your choice) to set a standard post value by key, and then access it the old fashioned way.
from django.utils import simplejson
data = simplejson.loads(request.POST['save'])
Which basically just reduces this handler method at this point to nothing more than a regular old Django view in terms of the steps you have to take to get it going.
So clearly, django-piston is not built to deal with files apparently?
My best idea here is that adding raw
string data directly to the POST body
and then adding a file just doesn't
work.
That wouldn't work, no. If you're POSTing form data using 'application/x-www-form-urlencoded' format, or 'multipart/form-data' you're not going to be able to just tack some extra data on the end - it needs to go in as part of the form data. Something like this I guess...
[request setPostValue:#"{\"save\":{\"name\":\"iostest\"}}" forKey:#"data"];
But if I remove the string data and only post the file it still doesn't work.
Is more problematic...
or if it's Piston erroneously misreading the data.
I probably wouldn't look in that direction first - piston doesn't really mess with the request object, so it seems more likely that the ASI request isn't quite right.
I think the place to start would be to inspect the incoming request and check that it really is a valid formPOST request:
Check that request["CONTENT_TYPE"] is set to 'multipart/form-data'
Inspect the request.raw_post_data and make sure that it is valid form data as specified in http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 - check that the key names are as you expected and that the file content is present. (Obviously you'll want to use a small text file when you're testing this!)
Check which keys actually are present in request.FILES, if any, in case it's as simple as something like a misnamed field.
Failing all that I'd try to narrow down if it's a problem on the client or server side by trying to write a plain python client and seeing if you have the same issue then. Looking around, something like this: http://atlee.ca/software/poster/ might be useful.