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.
Related
When DEBUG = False I know errors do get mailed to ADMINs, but I would like to see the errors on the screen if I am logged in as superuser.
Is there a way to trigger it to show the debug screen instead of the 500.html for public users?
As mentioned Sentry, or another service actually is a better choice. But for the case that you really want it your way, you would need a custom 500 handler and in there use django.views.debug.technical_500_response
https://docs.djangoproject.com/en/dev/_modules/django/views/debug/
There's no real documentation on this - except for a simple comment -, since it's a method that shouldn't really be used externally. But you're free to use it:
urls.py
urls.handler500 = views.handler500
views.py
def handler500(request):
if request.user.is_superuser():
return technical_500_response(some, params, dontaskme)
else:
return render(request, "500.html")
If you're not happy with the information generated in the emails, you're better off using something like Sentry to track what happens on your site so that you can see what users come up against.
It uses standard python logging so you can set what level sentry is triggered by, and have various messages in your app to tell you pieces of information, and it automatically picks up the warnings/errors that might occur. It gives you all the kind of information you get from the standard debug error page with the stacktrace, context information etc.
In my Django app, I'm getting a 404 Page Not Found response that looks like it's being caused by some logic in one of my custom template tags -- but I don't know which one.
Using Django Debug Toolbar's Request Vars panel, I can see the view causing the 404 is go_back.utils._register_wrapped_view -- which is how I know it's coming from one of my go_back.utils template tags.
Unfortunately, because template tags need to be decorated and thus show up as _registered_wrapped_view, I can't tell which tag it is, much less where in the tag code the problem happens. (The tag code is a special utility which works with urls and calls resolve in several places so it's not obvious.)
Thus I can't use the normal import pdb; pdb.set_trace() approach because I don't know where to set the trace.
So how can I get pdb to break when the 404 happens so I can see the stack trace leading to that point?
Try using the Django Debug Toolbar, it can intercept redirects, good for when you cant find where to add a breakpoint.
In settings make sure you have
DEBUG_TOOLBAR_CONFIG = {'INTERCEPT_REDIRECTS': True}
Old question, but there is django-pdb which has a post mortem flag for runserver. It doesn't look well maintained (2 years ago is the last commit), but it is simple middleware and updating it shouldn't be too hard.
I'm not sure if you know this:
You can try putting import pdb; pdb.set_trace() in the function which you want to debug and development server. When that function triggers it will break into pdb shell and you can debug your code.
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.
I have the following django URL:
url(r'^companies/$', 'companies', name='companies'),
If I go to http://localhost:8000/companies/ it works perfectly. However, if I try adding any GET variables to the URL django raises a 404. For example, if I go to http://localhost:8000/companies/?c=1 django raises a 404. What's strange, is that on the 404 it says:
The current URL, companies/, didn't match any of these.
Why am I not able to pass GET variables to my URLs?
I am using django 1.4.
The companies view is defined like:
def companies(request):
It shouldn't have to accept any additional parameters because they are GET variables, not URL parameters- correct? I swear I've done this hundreds of times and it always just works...
Okay. Figured out what was causing this very strange behavior. I have a custom context processor that is calling resolve(request.get_full_path()). Apparently that causes a 404 if there are any GET variables in the URL. Very strange.
I'm new to Django and have some code in my views.py like this:
try:
myfunction()
except:
assert False, sys.exc_info()[0]
This is very helpful because I get an email with lots of useful info if there's an error.
The problem is that it also redirects the user to a Webfaction system error page. What I'd like to know is how do I still get the useful error email, but redirect the user to my own error page?
Also, is this the best way to be handling errors in Django?
This is wrong on quite a few levels.
Firstly, there is no reason to catch an exception only to raise another one. If your application raises an exception, then Django's own middleware will catch it, and depending on whether or not you have DEBUG=True, either show a detailed debugging page, or mail the exception to the users mentioned in the ADMINS setting.
Secondly, you should never be getting a Webfaction error page - I can't even imagine how that is happening. If you want your users to see a nice error page, you should define 404.html and 500.html templates, or even full error-handling views if your needs are more complicated. This is fully explained in the documentation.
How about using mail_admins to mail yourself when something's up?
eg
from django.template.loaders import render_to_string
...
try:
#something cool but edgy here
except YourFavouriteException, yfe:
message_body = render_to_string('path/to/a/template/if/you/want.txt', {'exception': yfe, 'type_of_exception': type(yfe) } ## you could add more detail to this, of course
mail_admins('Something exploded', message_body)