Skip to content

Instantly share code, notes, and snippets.

View kezabelle's full-sized avatar

Keryn Knight kezabelle

View GitHub Profile
@kezabelle
kezabelle / get_or_set.py
Created September 25, 2013 11:01
Thing I want for caching in Django
class MyCacheBackendThing(Ellipsis):
def get_or_set(self, key, timeout, setter):
data = self.get(key, None)
if data is None:
data = setter
if callable(data):
data = data()
self.set(key, data, timeout)
return data
@kezabelle
kezabelle / templatetag.py
Last active December 24, 2015 12:09
Get the Django AdminSite.index() method, from any URL in the admin, in a template tag... hmm.
# there must be a better way :|
current_view = resolve(request.path)
root_url = reverse('%s:index' % current_view.app_name)
index_view = resolve(root_url)
# getting the actual AdminSite instance.
# This works on Python 2.
adminsite = index_view.func.func_closure[0].cell_contents
# this works on Python 2 and 3, because Python 3 seems to lack
# func_closure, and Python 2/3 have different ordering for the
@kezabelle
kezabelle / repr.py
Last active December 24, 2015 21:49
Is there a better way of constructing Python reprs than this? :|
class Hi(object):
def __repr__(self):
return '<{cls.__module__}.{cls.__name__} ... other stuff!>'.format(cls=self.__class__)
@kezabelle
kezabelle / wat.py
Created November 4, 2013 19:55
wat? when did this start?
Python 2.7.5 (default, Jun 22 2013, 15:34:23)
>>> wtf = {'a', 2}
>>> wtf
set(['a', 2])
@kezabelle
kezabelle / form.py
Created November 8, 2013 11:30
For omarek on IRC.
class MyForm(Form):
value = forms.ChoiceField(choices=())
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['value'].choices = get_choices(please_select='Please select:')
@kezabelle
kezabelle / loader.py
Created November 8, 2013 12:01
Sketching out a Django cached Loader which excludes some template patterns ...
from django.template.loaders import cached
from django.conf import settings
class Loader(cached.Loader):
""" mostly cached loader """
def load_template(self, template_name, template_dirs=None, exclusions=None):
if exclusions is None:
exclusions = getattr(settings, 'MOSTLYCACHED_EXCLUDES', ())
@kezabelle
kezabelle / forms.py
Created November 24, 2013 15:06
For Reflow on #django IRC
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['myfield'].label = 'hello'
class Meta:
model = MyModel
@kezabelle
kezabelle / thoughts.md
Last active December 29, 2015 15:29
Thoughts on rules on working in Django.
  • If you type MyModel.<manager>.filter anywhere, you're doing it wrong.
    • Either create a Manager and do it there, or, better yet, use django-model-utils's PassThroughManager and write a proper, chainable queryset.
    • Possibly better than that would just be to have a queries module, which contains functions that return the correct querysets. Seriously, tracking down queries being made is much easier if there's only one place to look.
  • If you're doing MyInstance.<related_name>.filter, I still hate you. Fix your manager/queryset or do that queries module I mentioned.
  • If you want to do anything to a field on a Form, do it via self.fields[<fieldname>] in the __init__ method. Everything else is crap.
  • If you're using a context processor and it touches the database, you'd better make it lazy() or I'll mow you down.
    • Seriously, otherwise it'll do queries for every RequestContext using view, even if it doesn't get used.
  • Use django-pdb, django-debug-toolbar and `django-devs
@kezabelle
kezabelle / explain.py
Created November 28, 2013 15:16
For NBhosting in #django IRC.
def runme():
return 1
def dontrunme():
return 2
a = {
'key1': runme,
'key2': runme,
'key3': dontrunme,
@kezabelle
kezabelle / ohlazy.py
Created November 30, 2013 17:35
None as a lazy() result...
>>> from django.utils.functional import lazy
>>> lazy(lambda: None, None)()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "django/utils/functional.py", line 181, in __wrapper__
return __proxy__(args, kw)
File "django/utils/functional.py", line 83, in __init__
self.__prepare_class__()
File "django/utils/functional.py", line 95, in __prepare_class__
for type_ in reversed(resultclass.mro()):