Source

django-odb / odb / models.py

Full commit
from django.http import HttpResponse
from odb.forms import MyForm, ManageForm
from django.template.base import Template
import shelve
from django.forms.forms import DeclarativeFieldsMetaclass, Form
from django import forms
from django.shortcuts import render

class ManageContent(object):
    form_class = ManageForm
    def render(self, req):
        return self.form_class

class ContentObject(object):
    content = "Empty Object"
    manager = ManageContent
    def __init__(self, content="Empty Object"):
        self.content = content
    def render(self, req):
        return HttpResponse(self.content)
    def manage(self, req):
        return self.manager().render(req)

class ObjectGroup(dict):
    object_class = ContentObject

class Field(object):
    _content = None
    _counter = 0
    def __init__(self, content=None):
        if content:
            self.content = content
        self._counter = Field._counter
        Field._counter += 1
    def get_field_class(self):
        return forms.Field()
    def validate(self, value):
        return value
    def _set_content(self, value):
        self._content = self.validate(value)
    def _get_content(self):
        return self._content
    def _del_content(self):
        self._content = None
    content = property(_get_content, _set_content, _del_content, "Field Contents.")

class CharField(Field):
    _content = ""
    def get_field_class(self):
        return forms.CharField()
    def validate(self, value):
        if isinstance(value, str) or isinstance(value, unicode):
            return value
        raise ValueError

class TextField(Field):
    _content = ""
    def get_field_class(self):
        return forms.CharField(widget=forms.Textarea)
    def validate(self, value):
        if isinstance(value, str) or isinstance(value, unicode):
            return value
        raise ValueError

class IntegerField(Field):
    _content = 0
    def get_field_class(self):
        return forms.IntegerField()
    def validate(self, value):
        if not isinstance(value, int):
            raise ValueError
        return value

class BooleanField(Field):
    _content = False
    def get_field_class(self):
        return forms.BooleanField()
    def validate(self, value):
        if not isinstance(value, bool):
            raise ValueError
        return value

class Model(object):
    template_name = "odb/model.html"
    def __init__(self, *args, **kwargs):
        self.scan_fields()
        for k,v in kwargs.iteritems():
            getattr(self, k).content = v
    def scan_fields(self):
        # Used to upgrade older models to include new field attributes.
        self.fields = [f for f in dir(self) if isinstance(getattr(self,f),Field)]
    def __getstate__(self):
        state = {'fields':self.fields}
        for f in self.fields:
            state.update({f:getattr(self,f).content})
        return state
    def __setstate__(self, state):
        self.fields = state['fields']
        for f in self.fields:
            getattr(self, f).content = state[f]
    def get_form_class(self):
        fields = {}
        for f in self.fields:
            fields.update({f:getattr(self,f).get_field_class()})
        return DeclarativeFieldsMetaclass(self.__class__.__name__+"Form", (Form,),fields)
    def get_initial(self):
        initial = {}
        for f in self.fields:
            initial.update({f:getattr(self,f).content})
        return initial
    def get_form(self):
        return self.get_form_class()(initial=self.get_initial())
    def process_form(self, form):
        if form.is_valid():
            for k,v in form.cleaned_data.iteritems():
                getattr(self, k).content = v
            return True
        return False
    def get_context_data(self, **kwargs):
        context = kwargs
        obj = []
        for k, v in self.get_initial().iteritems():
            obj.append({'name':k,'value':v})
        context.update({'object':obj, 'class':self.__class__.__name__})
        return context
    def render(self, req):
        return render(req, self.template_name, self.get_context_data(path=req.path))

class Person(Model):
    name = CharField()
    age = IntegerField()
    bio = TextField()
    is_staff = BooleanField()

odb_dict = shelve.open("mydata", writeback=True)

odb_dict3 = {'hello_odb': ContentObject("Hello ContentObject!"),
            'docs': ObjectGroup()}

odb_dict2 = {'hello_odb': HttpResponse("Hello Object Database!"),
            'test123': {'file.txt': HttpResponse("Hello World!"), 'me':"My name is Kevin!"},
            'myform': MyForm,
            'templates': {'index': "Not allowed.", 'odb': {'form.html': Template("<table>{{form}}</table>")}},
            'index': Template("{{GET.name}}")}