Skip to content

Instantly share code, notes, and snippets.

View kezabelle's full-sized avatar

Keryn Knight kezabelle

View GitHub Profile
@kezabelle
kezabelle / oh_formsets.py
Created May 11, 2016 14:48
for drvid on #django IRC.
class UserFormSet(BaseInlineFormSet): # or whatever. They all have __init__ and _construct_form and _empty_form
def __init__(self, user, *args, **kwargs):
self.user = user
super(UserFormSet, self).__init__(*args, **kwargs)
# Note: in master, at least, this is is all unnecessary, because there's a
# get_form_kwargs method you can use instead of either of these methods.
def _construct_form(self, i, **kwargs):
kwargs.update(user=self.user)
return super(UserFormSet, self)._construct_form(i, **kwargs)
from __future__ import unicode_literals
from wrapt import ObjectProxy
class Callable(ObjectProxy):
def __call__(self, *args, **kwargs):
result = self.__wrapped__
if 'upper' in kwargs:
result = result.upper()
return result
@kezabelle
kezabelle / fix_unicode_fun_characters.py
Last active April 6, 2016 13:06
Because unicode is fun, there are multiple characters for spaces, dashes, etc. Some of which have HTML equivalents, such as "NO-BREAK SPACE" which I don't want to respect, as the data source may supply that, but the output destination doesn't expect that.
from __future__ import unicode_literals
import unicodedata
import ftfy
import re
"""
Taken from:
https://www.cs.tut.fi/~jkorpela/chars/spaces.html
https://en.wikipedia.org/wiki/Whitespace_character#Unicode
@kezabelle
kezabelle / be_contiguous.py
Last active March 9, 2016 12:56
Generate contiguous groups of integers in python. Mostly for generating range/between + exacts in Django/Haystack where parameters may have a max count (sqlite, lucene I'm looking at you!)
import itertools
import operator
def contiguous(unsorted):
def grouper(value):
return value[0] - value[1]
data = sorted(unsorted)
for k, g in itertools.groupby(enumerate(data), grouper):
yield map(operator.itemgetter(1), g)
@kezabelle
kezabelle / sets.py
Created February 9, 2016 09:18
Oh python, why are you so silly.
>>> set([1]) - set([1])
set([])
>>> set([1]) + set([1])
TypeError: unsupported operand type(s) for +: 'set' and 'set'
@kezabelle
kezabelle / forms.py
Created February 3, 2016 09:01
form class generator factory, because playing around in __init__ is grim.
def generator(**kwargs):
display_fields = ['field1', 'field2']
qs = Model.objects.all()
if 'instance' in kwargs and kwargs['instance']:
qs = Model.objects.filter(type=kwargs['instance'].object_type)
if 'request' in kwargs and kwargs['request']:
if kwargs['request'].user.is_anonymous():
display_fields.remove('field2')
@kezabelle
kezabelle / modeladmin.py
Created January 21, 2016 11:09
for rramirez on #django IRC.
class MyModelAdmin(ModelAdmin):
list_display = ['mycallable']
list_display_links = [] # must not include mycallable.
def mycallable(self, obj):
return '<a href="%s">%s</a>' % (reverse('...'), obj)
mycallable.allow_tags = True
mycallable.short_description = "Column title"
@kezabelle
kezabelle / lolwut.py
Created January 20, 2016 14:39
a weird mishmash of doing an SQL "IN (x, y, z)" and covering consecutive ranges. For Django. Using Q objects and horrifying machinations.
def generate_integer_pk_range(flat_iterable):
"""
A bit of this is taken from :
http://code.activestate.com/recipes/496682-make-ranges-of-contiguous-numbers-from-a-list-of-i/#c2
and a bit from:
https://github.com/kezabelle/django-inheritrix/blob/a4825612dbcc20add509c4bb49e93bdb1f8f409f/inheritrix.py#L44
>>> x = MyModel.objects.values_list('pk', flat=True)
[1, 2...5, 9, 100...121]
>>> y = generate_integer_pk_range(x)
@kezabelle
kezabelle / celery_tasks.py
Created January 20, 2016 13:24
For ND1 in #django IRC.
@periodic_task(crontab(...))
def taskmaster():
acted_on = set()
for x in MyModel.objects.filter(...).iterator():
single_item.delay(model_id=x.pk)
acted_on.add(x.pk)
return acted_on
@task
@kezabelle
kezabelle / abstract-concrete.md
Created November 13, 2015 14:40
Moving from abstract to concrete inheritance in Django .... maybe.

step 1

Define a new Model ConcreteThing object pointing a the new base table. Only field is PK. Migrate it into place without changing anything else.

step 2

add a new field on the subclass which should ultimately inherit from ConcreteThing. The field is a OneToOneField to it, which is nullable.

step 3