Skip to content

Instantly share code, notes, and snippets.

@dfalk
Forked from patrys/abstract.py
Created February 7, 2012 04:46
Show Gist options
  • Save dfalk/1757258 to your computer and use it in GitHub Desktop.
Save dfalk/1757258 to your computer and use it in GitHub Desktop.
Parametrized apps for Django
class AbstractMixin(object):
_classcache = {}
@classmethod
def contribute(cls):
return {}
@classmethod
def construct(cls, *args, **kwargs):
attrs = cls.contribute(*args, **kwargs)
attrs.update({
'__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()):
pass
class MyProduct(factories.ProductFactory.construct(category=MyCategory)):
pass
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):
return self.name
class ProductFactory(models.Model, abstract.AbstractMixin):
name = models.CharField(max_length=100)
class Meta:
abstract = True
@classmethod
def contribute(cls, category):
return {'category': models.ForeignKey(category)}
def __unicode__(self):
return u'%s / %s' % (self.category, self.name)
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