Skip to content

Instantly share code, notes, and snippets.

View kezabelle's full-sized avatar

Keryn Knight kezabelle

View GitHub Profile
@kezabelle
kezabelle / gist:5481668
Created April 29, 2013 13:49
Oh god why :(
app/docs/forms.rst:4: WARNING: autodoc: failed to import module u'app.forms'; the following exception was raised:
Traceback (most recent call last):
File "path/to/sphinx/ext/autodoc.py", line 326, in import_object
__import__(self.modname)
File "app/forms.py", line 8, in <module>
class MyAppForm(ModelForm):
File "path/to/django/forms/models.py", line 206, in __new__
opts.exclude, opts.widgets, formfield_callback)
File "path/to/django/forms/models.py", line 160, in fields_for_model
formfield = f.formfield(**kwargs)
@kezabelle
kezabelle / search_indexes.py
Created May 5, 2013 20:08
Haystack indexing support for both 1.2 style, and the new 2.0 style classes.
import logging
from haystack.fields import CharField # Whatever fields you want ...
from myapp.models import MyModel
logger = logging.getLogger(__name__)
try:
# haystack 1.2x
from haystack import site
from haystack.indexes import SearchIndex
@kezabelle
kezabelle / logentry_author.py
Created June 5, 2013 11:04
Get the author of any object, in a generic way, assuming the content was administered through the Django admin.
def author(self):
entries = (LogEntry.objects
.filter(content_type=ContentType.objects.get_for_model(self), object_id=self.pk)
.filter(Q(action_flag=ADDITION | Q(action_flag=CHANGE)))
# switch to -action_time if you want the last edit, rather than the first.
return entries.order_by('action_time')[:1][0]
@kezabelle
kezabelle / another_way.py
Last active December 18, 2015 09:59
Create a model subclass, from a parent superclass, in Django, while using concrete inheritance ... hmmm
class MySuperClass(Model):
# some stuff follows ...
pass
class MySubClass(MySuperClass):
# unique fields
pass
obj = MySuperClass.objects.get(pk=1)
@kezabelle
kezabelle / gist:5765278
Created June 12, 2013 13:34
Apparently Django's add_to_class can magically sidestep the inability to specify fields of the same name (potentially across models?)
>>> from uuid import uuid4
>>> from django.db import models
>>> from django.contrib.auth.models import User
>>> User.objects.create(username=str(uuid4()))
<User: >
>>> User.add_to_class('username', models.CharField(max_length=300))
>>> User.objects.create(username=str(uuid4()))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/django/db/models/manager.py", line 137, in create
@kezabelle
kezabelle / disable_submits.js
Created June 14, 2013 09:36
Reminder to self about disabling submits ... built to work with Django's jQuery version (1.4.2) so passing in the selector as part of the live arguments doesn't work :\
var disable_elements = function(evt) {
// `this` is the form being submitted, in the current context ...
$(this)
.find('input[type="submit"], button, a.button')
.addClass('disabled')
.attr('readonly', 'readonly')
.attr('disabled', 'disabled')
.css({opacity: 0.5});
// note: the css and disabled parts may need removing, depending
// on needs (ie: the css could be set on the `disabled` class)
@kezabelle
kezabelle / mark_checkboxes.js
Created June 14, 2013 14:42
A reminder to myself about how to mark up wrapped checkboxes when they change ... could do with being cleverer, I expect.
$('input[type="checkbox"]').live('change', function(evt) {
var $this = $(this);
var $parent = $this.parent();
if ($this.attr('checked') === true) {
$parent.addClass('selected').removeClass('unselected');
return true;
} else {
$parent.removeClass('selected').addClass('unselected');
return false;
}
@kezabelle
kezabelle / crap_filter.js
Created July 23, 2013 09:22
Quick and dirty filtering in JavaScript ... inefficient!
var previous_result = '';
// listen to an input ...
$('#filter-input').live('keyup', function(evt) {
var filtering_by = $(this).val().toLowerCase();
if (previous_result === filtering_by) {
return;
}
previous_result = filtering_by;
// eg: labels, list items, whatever.
var possibles = $('#nodes-to-filter');
@kezabelle
kezabelle / settings.py
Created September 9, 2013 13:08
an attempt to document a 'perfect' connection string for MySQL.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS':{
"init_command": "SET storage_engine=INNODB, collation_connection='utf8_unicode_ci', sql_mode='TRADITIONAL', NAMES 'utf8';",
},
},
}
@kezabelle
kezabelle / paginator.py
Created September 24, 2013 11:16
Expose a method on the paginator for treating the original input as chunks, without needing to have nested forloops. This is so that big querysets can be chunked into smaller result sets (ie: less memory usage), at the cost of increased query throughput. I thought this'd be harder.
from django.core.paginator import Paginator
class ChunkingPaginator(Paginator):
def chunked_objects(self):
"""
Usage:
bigqs = ChunkingPaginator(Model.objects.all(), 100)
for obj in bigqs.chunked_objects():
# do something with the obj
pass