Skip to content

Instantly share code, notes, and snippets.

View tuatara's full-sized avatar

Matt Cooney tuatara

View GitHub Profile
@tuatara
tuatara / pre-commit
Created July 26, 2016 00:06
Lint python files on commit
#!/bin/sh
# Make executable, and save in .git/hooks
# Happily, flake8 will ignore non-python files
git diff --cached --name-only --diff-filter=ACM | flake8
@tuatara
tuatara / models.py
Created December 1, 2015 22:39
Custom `length` lookup for Django ORM
class LengthLookup(models.Transform):
lookup_name = 'length'
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return 'CHAR_LENGTH(%s)' % lhs, params
# SQLite doesn't implement CHAR_LENGTH, but its implementation of LENGTH conforms
# with standard SQL CHAR_LENGTH (i.e. number of chars, not number of bytes)
def as_sqlite(self, compiler, connection):
@tuatara
tuatara / local_settings.py
Created November 13, 2015 20:40
Use active git branch in Django’s DATABASES['NAME'] setting to help manage conflicting state
import subprocess
dbname = 'mydbname.{}.db'.format(
subprocess.check_output(['git', 'symbolic-ref', '--short', 'HEAD',]).rstrip()
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': path.join(BASE_DIR, dbname),
}
@tuatara
tuatara / admin.py
Last active April 7, 2021 21:23
Allow case-insensitive usernames with Django & Postgres
# Add the mixin to the default admin objects
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as ContribUserAdmin
from django.contrib.auth.forms import UserChangeForm as ContribUserChangeForm, \
UserCreationForm as ContribUserCreationForm
from accounts.forms import CaseInsensitiveUsernameMixin # adjust if forms.py is not in `accounts` app
class UserChangeForm(CaseInsensitiveUsernameMixin, ContribUserChangeForm):