Introduction
This is an article where there is a connection with the previous article. That article is an article with the title of ‘How to Configure Logging Feature to print variable in Django Application’. The article itself exist in this link. Apparently, this article is giving a simpler approach by using only the ‘views.py’ file of a Django-based application. The following is the content of the ‘views.py’ :
from django.shortcuts import render from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse from .models import Unit @login_required(login_url="/login/") def home(request): unit = Unit.objects.all()
Printing Variable in Django View to a Console
So, using the above script or source code, this part will show only using the ‘views.py’ to be able to print a variable into the console. The following are the sequences for doing that :
-
First of all, just import the logging library by adding the following line :
import logging
-
Next, in the function where the variable exist, just define the logging level by adding the following line :
logging.basicConfig(level=logging.INFO)
- Continue on the previous step, just define the logger variable using the following line :
logger = logging.getLogger('myapp')
- Finally, just print the variable to the console using the following line :
logger.info(unit)
So, overall, the above code will be in the following definition :
from django.shortcuts import render from django import template from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse from .models import Unit import logging @login_required(login_url="/login/") def home(request): unit = [] logging.basicConfig(level=logging.INFO) logger = logging.getLogger('myapp') logger.info(unit)