views:

24

answers:

1

Hey Guys,

How would you go about making a pluggable django app, that can accept data from any model and then perfom some action with that data (i.e Save to DB, Send email). This functionality should be generic and should not be tied to a specific model.

A: 

It depends on what functionality your app would provide and in what way you'd expect users of your app to use it's api. For interacting with other models you don't know about there are a few ways, depending on what your reusable app does. You can make forms, views etc that would accept a model class or instance as a property or parameter. The other way would be for the users of your app to specify their relevant models in settings.py much like auth deals with user profiles. For example if your app needs to know about a model class that provides info about gadgets the user would specify:

#user's settings.py
GADGETS_MODEL='myapp.CustomSuperFunGadgets'

To get the class for the user specified model you would do:

from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
if not getattr(settings, 'GADGETS_MODEL', False):
        raise ImproperlyConfigured('You need to set GADGETS_MODEL'
                                          'in your project settings')
try:
    app_label, model_name = settings.GADGETS_MODEL.split('.')
except ValueError:
    raise ImproperlyConfigured('app_label and model_name should'
                    ' be separated by a dot in the GADGETS_MODEL set'
                    'ting')

try:
    model = models.get_model(app_label, model_name)
    if model is None:
              raise ImproperlyConfigured('Unable to load the gadgets '
                    'model, check GADGETS_MODEL in your project sett'
                    'ings')
except (ImportError):
     raise ImproperlyConfigured('Unable to load the gadgets model')
#at this poing model will hold a reference to the specified model class

Another way of interacting with models you don't know about is your app to provide custom model fields or managers or special properties that would just attach signal handlers to the model they are attached to.

As I said it all depends on what problem your reusable app is trying to solve, and the approach you should take is always based on that.

Vasil