Working Ninja
2017-03-23T17:22:08

Here's a simple way to count lines of code via the command line that I recently used for a Django project:

find . -name '*.py' -not -path "*/migrations/*" | xargs wc -l

or

wc -l **/*.py

Source: http://stackoverflow.com/questions/1358540/how-to-count-all-the-lines-of-code-in-a-directory-recursively#1358573

2017-02-16T15:41:13
#!/usr/bin/python
import sys


try: 
    hex_val = str(sys.argv[1])
except Exception as e:
    sys.exit('Please provide a hex code as an argument (e.g. hex2rgb 333333).')

r = int(hex_val[0:2], 16)
g = int(hex_val[2:4], 16)
b = int(hex_val[4:6], 16)

print('{}, {}, {}'.format(r, g, b))

Append your ~/.bash_aliases with:

alias hex2rgb="~/bin/hex2rgb.py"

Load the new alias:

$ source ~/.bash_aliases

Now we're able to convert Hex to RGB from the command line:

$ hex2rgb e1e1e1
255, 255, 255
2017-02-10T16:39:53

Somehow, somewhere, something happened to my migrations. It had been a few months since I had edited my models.py file and out of the blue I ended up with an issue adding an additional field to a model. I search around Stack Overflow and found a great answer that resolves this (hopefully it doesn't happen to you!). Here's what the recommendation was:

./manage.py migrate --fake <app-name> zero
rm -rf <app-name>/migrations
./manage.py makemigrations <app-name>
./manage.py migrate --fake <app-name>

If you ran into this issue at the same time that I did (when adding a new field to a model), comment out the field you just added before you run any of the above commands (also comment out any additional new changes you may have made). If you don't, the last migrate --fake will include your new field/changes without generating a new migration file for it.

Source: https://stackoverflow.com/questions/23755523/how-to-reset-migrations-in-django-1-7

2016-11-21T23:42:35
import logging

logging_config = {
    'filename': '/var/log/app_log',
    'format': '%(asctime)s [%(levelname)s] %(message)s',
    'level': logging.INFO
}
logging.basicConfig(**logging_config)

logging.info('Our logged message.')

This will output the following to /var/log/app_log:

2016-11-21 23:50:53,677 [INFO] Our logged message.

Source: https://docs.python.org/2/howto/logging.html#logging-basic-tutorial

2016-11-21T23:35:33

The Old Way

import os

os.system('find /home/user/documents -type f -iname "*.doc"')

The New, Recommended Way

import subprocess

subprocess.check_call([
    'find',
    '/home/user/documents',
    '-type', 'f',
    '-iname', '*.doc'
])

Bonus Tidbit

At this point, we can incorporate some nice exception handling:

import subprocess

try:
    subprocess.check_call([
        'find',
        '/home/user/documents',
        '-type', 'f',
        '-iname', '*.doc'
    ])
except subprocess.CallProcessError as e:
    print e.returncode
    print e.cmd
    print e.output

See the official Python Documentation for more usage and recommendations on the subprocess module.

2016-11-11T16:55:21
import json

polls = Poll.objects.all()

# Convert our QuerySet into a list so polls can be serialized
print json.dumps(list(p), indent=2)
JsonResponse({'polls': list(polls)})

Source: http://stackoverflow.com/questions/7650448/django-serialize-queryset-values-into-json

2016-11-03T20:05:28
import json
import psycopg2
from psycopg2.extras import RealDictCursor

cursor = conn.cursor(cursor_factory=RealDictCursor)
objects = cursor.fetchall()

print json.dumps(objects, indent=2)

# Django
#JsonResponse({'objects': objects})

Source: https://www.peterbe.com/plog/from-postgres-to-json-strings

2016-09-06T07:51:45
#!/usr/bin/env python

import os

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'

import django
django.setup()

from app.models import Class

# Your scripting here.

Sources:
https://docs.djangoproject.com/en/1.10/intro/tutorial02/#playing-with-the-api
https://docs.djangoproject.com/en/1.10/topics/settings/#on-the-server-mod-wsgi

2016-08-29T22:49:43

Set the end date with the current date and time and the start date 1 week prior:

import datetime

start_date = datetime.datetime.now() - datetime.timedelta(days=7)
end_date = datetime.datetime.now()
2016-03-30T21:57:36

I was attempting to make a directory listing of sorts earlier tonight and couldn't think up a clean solution. Some surfing on the world wide web offered up a quick template tag solution.

For example, say we have a list of objects (Person) from our app's view, [<Person: Doe>, <Person: Li>, <Person: Smith>, ...], and want to only print the first letter of their last name.

We can do this by first taking the string person.last_name and turning it into a list. Then, to snag just the first item from our newly formed list.

Template Tag with Filter(s) Rendered Output
{{ person.last_name }} Doe
{{ person.last_name|make_list }} ['D', 'o', 'e']
{{ person.last_name|make_list|first }} D

Profit!

Source: http://stackoverflow.com/questions/26058602/want-to-display-the-first-character-of-word-in-django-templates