Some utils file in django
Some important feature that are useful in dajngo application
0.Some important command in Djnago
tqdm is used to show a smart progress meter in Django shell.
pip install tqdm
Example (shell)
from tqdm import tqdm
queryset = MyModel.objects.all()
for data in tqdm(queryset):
# mycode
How to reload django shell
You can refresh code in shell without restarting a shell using reload module imported form importlib
>>> from my_app import my_file
>>> my_file.my_function()
# reload my_file
>>> from importlib import reload
>>> reload(my_file)
>>> my_file.my_function()
How ro setup dajngo shell plus and ipython
shell_plus is a management command to start the shell and it automatically imports all the models and DateTime module
INSTALLATION
First Run this command
pip install ipython==7.3.0
pip install ipython-genutils==0.2.0
pip install django-extensions==2.1.7
pip install jedi==0.17
Now add django_extensions in installed-app
INSTALLED_APPS = [
...
'django_extensions',
]
USAGE
Once installed, then run:
python manage.py shell_plus --ipython
This will open shell and import all the models in shell
pip install -r requirements.txt
pip list
pip freeze > requirementx.txt
pip freeze
1.Email configuration
import random
import smtplib
from django.db import transaction
with transaction.atomic():
user = User.objects.get(email=email)
otp = ''.join([str(random.randint(0, 9)) for i in range(6)])
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('egurulearning1@gmail.com', 'pbhugmqyndwsmzbd')
msg = f"hello{user.username} your otp code is {str(otp)}"
server.sendmail("egurulearning1@gmail.com", email, msg)
server.quit()
user.otp = otp
user.save()
2.Logging File In django
Logging helps the developer debug the error and track events.
Logging configuration:
Logging consists of four parts:-
- Loggers
- Handlers
- Filters
- Formatters
Loggers
Logger is the entry point into the logging system they configured to have log level. The log level indicates the severity of the message.
Log Levels
- DEBUG -- Low-level system info
- INFO -- Gernal System info
- WARNING -- Small problem-related info
- ERROR -- Major problem-related info
- CRITICAL -- Critical problem-related info
Handlers
Handler decides what happens to each message. Example message to be written on a screen or a file etc.
Filters
Filters are used to filter the log recourds
Formatters
Formatters decides the format of the log created
settings.py
# we don't need to import LOGGING
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"format": "%(asctime)s %(name)s %(levelname)s %(message)s",
},
},
"handlers": {
"console": {
# console handler show logs on terminal console
"class": "logging.StreamHandler",
"formatter": "console"
},
"default_file": {
# default_file handler saves logs in default.log file
"class": "logging.FileHandler",
"formatter": "console",
"filename": BASE_DIR + '/default.log', # or BASE_DIR / 'default.log'
},
"djagno_file": {
# djagno_file handler saves logs in django.log file
"level": "ERROR",
"class": "logging.FileHandler",
"formatter": "console",
"filename": BASE_DIR + '/django.log', # or BASE_DIR / 'django.log'
},
},
"loggers": {
# default for all undefined Python modules
"": {
"handlers": ["console", "default_file"],
"propagate": True,
},
# For django logs
"django": {
"handlers": ["djagno_file"],
"level": "ERROR",
"propagate": True,
},
},
}
Example-2
If you want to save logs of all the levels (DEBUG, INFO, WARNING, ERROR and CRITICAL) then remove level from loggers and handlers
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"handlers": {
"djagno_file": {
"class": "logging.FileHandler",
"filename": BASE_DIR + '/django.log',
},
},
"loggers": {
"django": {
"handlers": ["djagno_file", ],
"propagate": True,
},
},
}
Disable logging:
You can set LOGGING_CONFIG to None to disable the logging
settings.py
LOGGING_CONFIG = None
Trigger custom log
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
def hello(request):
# for warning
logger.warning('this is my warning')
# for error
logger.error('this is my error')
# for critical
logger.critical('this is my critical error')
Example-4
#settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'timestamp': {
'format': '{asctime} {levelname} {message} {lineno} ',
'style': '{',
},
},
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': BASE_DIR / 'debug.log',
'formatter': 'timestamp'
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
},
}
In which python file you need to track loggin , import below code, then debug will be track.
import logging
logger = logging.getLogger('django')
Note: Donot forget to add it into .gitignore file
*.log
Generate password
import string
import secrets
letters = string.ascii_letters
digits = string.digits
special_chars = string.punctuation
alphabet = letters + digits + special_chars
def generate_password():
pwd = ''
for i in range(8):
pwd += ''.join(secrets.choice(alphabet))
return pwd
Generate pdf and send email
# pip install xhtml2pdf==0.2.9
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.http import HttpResponse
from django.core.mail import EmailMessage
def render_to_pdf(template_src, context_dict={}):
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
##for sending email
json_data = serializer_data
current_date = datetime.now()
html_content = {"data": json_data, "created_at": current_date, 'title': f'{self.request.GET.get("type")} Report', "total_count": total_count,
"total_sales": total_sales,
'total_sales_after_tax': total_sales_after_tax,
"issued_by": request.user}
pdf = render_to_pdf('Email/report.html', html_content)
email = EmailMessage(
f'Report On Sales By Customer',
'Report On Sales By Customer',
settings.DEFAULT_FROM_EMAIL,
[self.request.user.email]
)
email.attach('file.pdf', pdf.getvalue(), 'application/pdf')
email.send()
return HttpResponse(pdf, content_type='application/pdf')