Working Ninja

By default, a ModelForm is populated with all its objects from the database. Sometimes it's desirable to limit these results as they are returned to the view. After setting up our ModelForm ( there is only one thing we need to do to make this happen. Within our view (, we update the queryset as follows:

class PollForm(ModelForm):
    class Meta:
        model = Poll
        fields = ('question',)

form = PollForm()
form.fields['question'].queryset = Poll.objects.filter(question__startswith="How")

This will filter Polls that start with "How".



The following example looks for the "idle" time before backlight brightness is reduced.

Find what you're looking for:

gsettings list-recursively | grep idle

Get the value:

gsettings get org.gnome.settings-daemon.plugins.power idle-brightness

Set the value:

gsettings set org.gnome.settings-daemon.plugins.power idle-brightness 120



Create unicode string "a".

>>> a = u'\u2019'
>>> a

Convert to ASCII string (ASCII is default for Python 2 str()).

>>> str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128)

Encode the unicode string to UTF-8 (overriding the default of ASCII).

>>> str(a.encode('utf-8'))
>>> print str(a.encode('utf-8'))

For a greater understanding, see Ned Batchelder's great "Pragmatic Unicode, or, How do I stop the pain?" (2012) video.


Let's say we want to query our Polls app for all Questions that have popular (more than 5 votes) choices that contain Python in the choice_text.

We could query our database as follows:

SELECT * FROM question JOIN (SELECT * FROM choice WHERE vote_count > 5 AND choice_text LIKE '%Python%') choice ON = choice.question_id;

Or, it can be codified in a potentially more comprehendable, OOP/ORM format with SQLAlchemy.

First, we set up our schema by declaring the relationship and the parameters of the join:

class Question(Base):
    __tablename__ = 'question'

    id = Column(Integer, primary_key=True)

    popular_choices = relationship('Choice', primaryjoin='and_( == Choice.question_id, Choice.vote_count > 5')

Next, we query with SQLAlchemy's ORM:

popular_python_choices = session.query(Question) \
    .filter(Question.popular_choices.contains('Python') \

Not quite as terse as straight SQL but hopefully it is clear how, after the schema is set up, calling Question.popular_choices.contains('Python') provides increased readability (reads like English) and reusability (replace our filter Python with whatever you wish!).

SQLAlchemy provides another good example.


Here's the most straightforward and succinct way I've found to mock patch a function that returns different (but specific) results with each call, shamelessly copied from Python Docs:

>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
...     return values[arg]
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)

And, now that we have our side_effect function defined, we can pass new values to return:

>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)



After updating mysql-connector-python to 8.0.11 (released April 19, 2018), I received an "OperationalError: 1043 (08S01): Bad handshake" error when querying a MySQL database. I found that I needed to set 'use_pure: True' in the connection string.

From the MySQL folks:

The C extension was added in version 2.1.1 and is enabled by default as of 8.0.11. The use_pure option determines whether the Python or C version of this connector is enabled and used.1

For example2:

import mysql.connector

config = {
  'user': 'scott',
  'password': 'password',
  'host': '',
  'database': 'employees',
  'use_pure': True,

cnx = mysql.connector.connect(**config)

Since I don't have the C extension installed on my server, I reverted back to the Python implementation. Though it is good to know that the C extension can improve performance for large queries--something to tuck away for future use.



Toggle all <option>'s as checked/unchecked with the click of a <button>.


    jQuery("select :checkbox").each(function(){
        this.checked = !this.checked;



If you've ever touched a date or time related field via the Django API, you'll have noticed the big warning that the date and/or time is not localized. While the warning is nice there isn't much more in the way of how to localize the time. Here are two ways that I usually go about it:

>>> timezone.make_aware() 
>>> timezone.localtime()

Both are found in django.utils's timezone module. If you're using Django Extensions, timezone is already loaded when you run ./ shell_plus. If you're not, simply run from django.utils import timezone.

For usage:

>>> help(timezone.make_aware)
>>> help(timezone.localtime)

Give your hand some relief from reaching for Ctrl and take advantage of the close proximity of Caps Lock.

# Note any previous values for xdb-options (most likely none)
gsettings get org.gnome.desktop.input-sources xkb-options

# Set our xkb-options (plus anything from our get, if needed)
gsettings set org.gnome.desktop.input-sources xkb-options "['ctrl:nocaps']"

Now to retrain your brain ;)




You should name a variable using the same care with which you name a first-born child (xxi).

Quality is the result of a million selfless acts of care--not just of any great method that descends from the heavens. That these acts are simple doesn't mean that they are simplistic, and it hardly means that they are easy. They are nonetheless the fabric of greatness and, more so, of beauty, in any endeavor. To ignore them is not yet to be fully human (xxii).

Chapter 2: Meaningful Names

Clarity is king (25).

Our goal, as authors, is to make our code as easy as possible to understand. We want our code to be a quick skim, not an intense study. We want to use the popular paperback model whereby the author is responsible for making himself clear and not the academic model where it is the scholar's job to dig the meaning out of the paper (27).

Chapter 3: Functions

Functions are the first line of organization in any program (31).

The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that (34).


So, another way to know that a function is doing more than "one thing" is if you can extract another function from it with a name that is not merely a restatement of its implementation (36).

Master programmers think of systems as stories to be told rather than programs to be written (49).

Chapter 4: Comments

The proper use of comments is to compensate for our failure to express ourself in code. Note that I used the word failure. I meant it. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration (54).

The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong. The reason is simple. Programmers can't realistically maintain them (54).

Truth can only be found in one place: the code (54).

It takes only a few seconds of thought to explain most of your intent in code. In many cases it's simply a matter of creating a function that says the same thing as the comment you want to write (55).

Plopping in a comment just because you feel you should or because the process requires it, is a hack (59).

Any comment that forces you to look in another module for the meaning of that comment has failed to communicate to you and is not worth the bits it consumes (60).

Others who see that commented-out code won't have the courage to delete it (68).

Chapter 5 - Formatting

Each line represents an expression or a clause, and each group of lines represents a complete thought. Those thoughts should be separated from each other with blank lines (78).

Have you ever hunted up the chain of inheritance for the definition of a variable or function? This is frustrating because you are trying to understand what the system does, but you are spending your time and mental energy on trying to locate and remember where the peices are. Concepts that are closely related should be kept vertically close to each other. Clearly this rule doesn't work for concepts that belong in separate files. But then closely related concepts should not be separated into different files unless you have a very good reason.  Indeed, this is one of the reasons that protected variables should be avoided (80).

All quotes from Clean Code: A Handbook of Agile Software Craftsmanship by Robert C Martin.