Django testshell
This commands runs a Python interactive interpreter with test database and data from the given fixture(s). It is usable if you want to play with test database.
See also testserver docs
from django.core.management.base import BaseCommand
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list
help = 'Runs a Python interactive interpreter with test database and data from the given fixture(s).'
args = '[fixture ...]'
requires_model_validation = False
def handle(self, *fixture_labels, **options):
from django.core.management import call_command
from django.db import connection
verbosity = int(options.get('verbosity', 1))
# Create a test database.
db_name = connection.creation.create_test_db(verbosity=verbosity)
# Import the fixture data into the test database.
call_command('loaddata', *fixture_labels, **{'verbosity': verbosity})
call_command('shell')
Switch between django trunk and stable versions
This is snippet that I use to switch development with Django between 1.0 and trunk versions:
#!/bin/sh
rm /Library/Python/2.5/site-packages/django
if [ "$1" = "" ]; then
echo "Django 1.0"
ln -s LOCATION_OF_SOURCE_CODE/django-1.0/django /Library/Python/2.5/site-packages/django
else
echo "Django trunk"
ln -s LOCATION_OF_SOURCE_CODE/django-trunk/django /Library/Python/2.5/site-packages/django
fi
$ ~/djchange.sh
Django 1.0
$ django-admin.py --version
1.0-final-SVN-8977
$ ~/djchange.sh trunk
Django trunk
$ django-admin.py --version
1.1 alpha 1 SVN-10065
Also check that django-admin.py is symbolic link to /Library/Python/2.5/site-packages/django/bin/django-admin.py
Rails - dump database structure for SQL Server
Dumping structure with rake db:structure:dump task when connecting to SQL Server will fail with scptxfr not found error.
command not found: scptxfr /s /d /I /F db /q /A /r
Thats documented in #3298. However dump of database structure can be easily achived from ActiveRecord:
script/console
>> ActiveRecord::SchemaDumper.dump
Satchmo product images
Templatetag for Satchmo creates unordered list for product images. CSS can be applied to customize output.
from django import template
from satchmo.product.models import Product
from satchmo.thumbnail.templatetags.satchmo_thumbnail import thumbnail
try:
from xml.etree.ElementTree import Element, SubElement, tostring
except ImportError:
from elementtree.ElementTree import Element, SubElement, tostring
register = template.Library()
default_opts = {
'thumbnail': 'width=280',
'start': 0
}
class ProductGalleryNode(template.Node):
def __init__(self, product, **opts):
self.product = template.Variable(product)
self.opts = default_opts
self.opts.update(opts)
def render(self, context):
actual_product = self.product.resolve(context)
images = actual_product.productimage_set.all()
start = int(self.opts['start'])
if len(images) <= start: return ("")
root = Element("ul", {'class': self.opts.get('class', '')})
for (i, pic) in enumerate(images[start:]):
li_attr = {'class': 'first'} if not i else {}
li = SubElement(root, 'li', li_attr)
link = SubElement(li, 'a', {'href' : pic.picture.url})
caption = pic.translated_caption()
src = thumbnail(pic.picture.url, self.opts.get('thumbnail'))
img = SubElement(link, 'img', {'src': src, 'alt': caption, 'title': caption})
return tostring(root, 'utf-8')
@register.tag
def product_gallery(parser, token):
""" Returns an unordered list of image thumbnails for product.
Usage:
{% product_gallery product %}
{% product_gallery product thumbnail="width=280"%}
{% product_gallery product start=1%}
{% product_gallery product class=galeria%}
"""
kwargs = {}
bits = token.split_contents()[1:]
product = bits[0]
for bit in bits[1:]:
arg, val = bit.split("=", 1)
kwargs[str(arg)] = val.strip('"')
return (ProductGalleryNode(product, **kwargs))
Satchmo categories
Here is the templatetag for use in Satchmo. It extend existing satchmo category_tree tag allowing customizing product categories. from_level and deep affect what part of tree would be displayed while select_parents makes all parent categories of active category selected.
from django.template import Library, Node, Variable, VariableDoesNotExist
from satchmo.product.models import Category
import logging
log = logging.getLogger('shop.templatetags')
try:
from xml.etree.ElementTree import Element, SubElement, tostring
except ImportError:
from elementtree.ElementTree import Element, SubElement, tostring
register = Library()
def recurse_for_children(current_node, parent_node, active_categories = [], show_empty=True, deep = -1, current_deep = 0):
child_count = current_node.child.count()
if show_empty or child_count > 0 or current_node.product_set.count() > 0:
temp_parent = SubElement(parent_node, 'li')
attrs = {'href': current_node.get_absolute_url()}
if current_node in active_categories:
attrs["class"] = "current"
link = SubElement(temp_parent, 'a', attrs)
link.text = current_node.translated_name()
if current_deep == deep: return
if not child_count: return
new_parent = SubElement(temp_parent, 'ul')
children = current_node.child.all()
for child in children:
recurse_for_children(child, new_parent, active_categories, show_empty, deep, current_deep + 1)
class SubcategoryTree(Node):
def __init__(self, active = None, from_level = 0, deep = -1, select_parents = 0):
self.active = active
self.from_level = int(from_level)
self.deep = int(deep)
self.select_parents = bool(select_parents)
def render(self, context):
root = Element("ul")
active_categories = []
root_categories = None
if self.active:
active_cat = Variable(self.active).resolve(context)
active_categories = [active_cat]
if self.select_parents: active_categories.extend(active_cat.parents())
if self.from_level:
parents = active_cat.parents()
parents.append(active_cat)
index = self.from_level - 1
if index > len(parents): return ("")
root_categories = parents[index].child.all()
else:
root_categories = Category.objects.root_categories()
else:
root_categories = Category.objects.root_categories()
for cats in root_categories:
recurse_for_children(cats, root, active_categories, deep = self.deep)
return tostring(root, 'utf-8')
@register.tag
def categories(parser, token):
"""
Creates an unnumbered list of the categories. It allows to specify deep and start level.
If select_parents all parent categories would have class="current" - this is suitable for main categories.
Examples:
{% categories %}
{% categories active=category from_level=1%}
{% categories active=category deep=0 select_parents=1 %}
"""
kwargs = {}
for bit in token.split_contents()[1:]:
arg, val = bit.split("=")
kwargs[str(arg)] = val
return (SubcategoryTree(**kwargs))
View archives for May 2009.
I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in