Debugging while developing Django apps - django

I'm aware of pdb built-in Python library for debugging Python programs and scripts. However, you can't really use it for debugging Django apps (I get errors when I try to use it in views.py). Are there any tools that I can use when Django's traceback isn't helpful ?
EDIT:
from .forms import TestCaseForm, TestCaseSuiteForm
from .models import TestCase, TestSuite
from django.contrib.auth.forms import UserCreationForm
from django.views.generic import FormView, ListView
from django.contrib.auth.models import User
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout
import pdb
class ListAllTestSuites(ListView):
template_name = 'list.html'
context_object_name = 'username'
def get_queryset(self):
pdb.set_trace() # <-- setting a trace here to diagnose the code below
queryset = {'test_suites': TestSuite.objects.filter(user=self.request.user),
'username': self.request.user}
return queryset

you forgot the exact error message and full traceback, and, more importantly, you forgot to explain how you executed this code to get this result...
But anyway: from the error message, you're obviously trying to execute your view file as a plain python script (cf the reference to __main__). This cannot work. A view is a module, not a script, and, moreover, any module dependending on Django needs some setup done to be imported (which is why we use the django shell - ./manage.py shell - instead of the regular Python one).
For most case, you can just launch the django shell, import your module and use pdb.runcall() to execute some function / method under the debugger (no need to put a breakpoint then, but that's still possible).
Now views require a HTTPRequest as first argument which make them a bit more cumbersome to debug that way (well, there is django.tests.RequestFactory but still...), so your best bet here is to set your breakpoint, launch your devserver (or restart it - if it didn't already did, as it should), point your browser to the view's url, and then you should see the debugger's prompt in your devserver's terminal.

Related

Problem to run a check in my database in django

I have created a model called Certs, the models is registered and it is showing in the admin page, however I am trying to call it to run a check and try to make a task, but I am getting the error: No module named 'ships',
This is the structure of my project (note I am writing the code in reminders.py):
And here my code:
from django.core.mail import send_mail
from ships.models import Certs
from datetime import datetime, timedelta
b = Certs.objects.count()
def notifications():
for dates in range(b):
if Certs.exp_date[b] <= datetime.datetime.now() - timedelta(days=30):
send_mail(subject='Test',message='This is a reminder where you will be reminded about expiring certifications', recipient_list=['info#intermaritime.org'])
Thank you very much
Add the ships module to your INSTALLED section of settings.py

dajaxice.core.js not updated with functions in ajax.py

I'm running Django (1.4.3) with dajaxice (0.5.4). I have a file ajax.py with my functions in the main project folder called prj, which looks like:
from dajax.core import Dajax
from dajaxice.decorators import dajaxice_register
from django.utils import simplejson
from dajaxice.core import dajaxice_functions
from django.core.urlresolvers import reverse, resolve
def getContent(request, *args, **kwargs):
url = kwargs['url']
try:
v = resolve(url)
except:
data = []
data.append(('some','data'))
return simplejson.dumps(data)
dajaxice_functions.register(getContent)
I ran python manage.py collectstatic, and I get the following output:
Copying '/tmp/tmpm8OlOw'
However, the dajaxice.core.js generated does not have my function getContent at all. Where am I going wrong? I have dajaxice installed properly and everything, I hope.
Seems you forgot to call dajaxice_autodiscover() from urls.py (this is the place recommended by dajaxice author)
this call will load ajax.py module and make it's method discoverable by JS code generator
You need to register you function with dajaxice either using #dajaxice_register decorator or other methods mention in the documentation.
http://django-dajaxice.readthedocs.org/en/latest/quickstart.html#create-your-first-ajax-function

Django app_cache_ready method returns True on Dev and False on production

I can't figure out what can be the reason.
On my dev machine the exactly same django project runs properly, while on production in the custom middleware code app_cache_ready() method always returns False. If I ignore and bypass it cache.set does not cache the object.
My dev environment uses runserver to launch the server, while the production uses Apache and mod_wsgi with virtualhost directives.
Does anyone have a clue what might be the problem? I have already spent couple of hours with no success.
Thanks in advance
Below is the simplified code that fails to cache again:
from django.conf import settings
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect, Http404
from django.core.cache import cache
from django.db.models.loading import app_cache_ready
from django.utils.cache import patch_vary_headers
class MyMiddleware(object):
def process_request(self, request):
key='kuku'
val=cache.get(key)
if not val:
logger.warn('Cached key is not available')
cache.set(key,5)
else:
logger.warn('Cached key is %s' % str(val))
With subsequent calls I see always Cached key is not available.

Calling a model's method from outside Django

I have a Django model with some static methods. I'd like to call the methods from outside the application (cronjob).
The model I have:
class Job(models.Job):
#Irrelevant information
#staticmethod
def methodIwantToCall():
#statements
I have the following python file that I'm using for the cron job:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from myapp.models import Job
Job.methodIwantToCall()
At first, I was having an error about DJANGO_SETTINGS_MODULE not being set and I fixed that, however, now I have the following error: No module named myapp.utils
I feel like I'm doing something that I'm not supposed to do. So how do I call that static method the way I want it to be called?
EDIT: It looks like the paths are getting messed up when I'm importing from outside Django. For example, I have an import in my models file, when I call the cron file it fails importing with the message ImportError: No module named myapp.utils even though it's working.
The proper solution is to create custom manage.py command.
Assuming your cron job code resides in the same directory as your settings file, use the following setup code at the beginning:
from django.core.management import setup_environ
import settings
setup_environ(settings)

django: debugging code in the view layer

I am developing my first django website.
I have written code in my view layer (the handlers that return an HttpResponse object to the view template (hope I am using the correct terminology).
In any case, I want to put print statements in my views.py file, so that I can debug it. However, it looks like stdout has been redirect to another stream, so I am not seeing anything printed out on my console (or even the browser).
What is the recommended way (best practice) for debugging django view layer scripts?
there are more advanced ways of doing it, but i find dropping
import pdb
pdb.set_trace()
does the job.
Use the Python logging module. Then use the Django debug toolbar, which will catch and display all the things you send to the log.
I'd upvote dysmsyd, but I don't have the reputation.
pdb is good because it lets you step thru your procedure and follow the control flow.
If you are using the django runserver, you can print to stdout or stderr.
If you are using the mod_wsgi, you can print to stderr.
The pprint module is also useful:
import sys
from pprint import pprint
def myview(request):
pprint (request, sys.stderr)
Try django-sentry. Especially if your project is in production stage.
Configure django debug toolbar: pip install django-debug-toolbar and follow the instructions to configure it in: https://github.com/django-debug-toolbar/django-debug-toolbar
import logging
Use the logging to debug: logging.debug('My DEBUG message')
Here is how it works on my class view:
from django.views.generic import TemplateView
import logging
class ProfileView(TemplateView):
template_name = 'profile.html'
def get(self, request, *args, **kwargs):
logging.debug(kwargs)
return render(request, self.template_name)