Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Parametrized apps for Django
class AbstractMixin(object):
_classcache = {}
def contribute(cls):
return {}
def construct(cls, *args, **kwargs):
attrs = cls.contribute(*args, **kwargs)
'__module__': cls.__module__,
'Meta': type('Meta', (), {'abstract': True}),
key = (args, tuple(kwargs.items()))
if not key in cls._classcache:
clsname = ('%s%x' % (cls.__name__, hash(key))) \
.replace('-', '_')
cls._classcache[key] = type(clsname, (cls, ), attrs)
return cls._classcache[key]
from yourapp import factories
class MyCategory(factories.CategoryFactory.construct()):
class MyProduct(factories.ProductFactory.construct(category=MyCategory)):
from django.conf.urls.defaults import patterns, include
from . import models
urlpatterns = patterns('',
url('^my-app/$', include('yourapp.urls'), {'product_model': models.MyProduct}),
from django.db import models
from . import abstract
class CategoryFactory(models.Model, abstract.AbstractMixin):
name = models.CharField(max_length=100)
class Meta:
abstract = True
def __unicode__(self):
class ProductFactory(models.Model, abstract.AbstractMixin):
name = models.CharField(max_length=100)
class Meta:
abstract = True
def contribute(cls, category):
return {'category': models.ForeignKey(category)}
def __unicode__(self):
return u'%s / %s' % (self.category,
from django.conf.urls.defaults import patterns, url
from . import views
urlpatterns = patterns('',
url('^(?P<id>\d+)/$', views.details),
from django.shortcuts import get_object_or_404
from django.views.generic.simple import direct_to_template
def details(request, product_model, id, template='example/details.html'):
product = get_object_or_404(product_model, id=id)
return direct_to_template(request, template, {'product': product})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.