public
Created

Django in single file with model and admin

  • Download Gist
mini_django.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
"""
Django in single file with model and admin. Based on:-
 
http://fahhem.com/blog/2011/10/django-models-without-apps-or-everything-django-truly-in-a-single-file/
"""
import sys
from os import path as osp
 
def rel_path(*p): return osp.normpath(osp.join(rel_path.path, *p))
rel_path.path = osp.abspath(osp.dirname(__file__))
this = osp.splitext(osp.basename(__file__))[0]
from django.conf import settings
SETTINGS = dict(
SITE_ID=1,
DATABASES = {},
DEBUG=True,
TEMPLATE_DEBUG=True,
ROOT_URLCONF = this
)
SETTINGS['TEMPLATE_DIRS'] = (rel_path(),),
SETTINGS['DATABASES']={
'default':{
'ENGINE':'django.db.backends.sqlite3',
'NAME':rel_path('db')
}
}
 
SETTINGS['INSTALLED_APPS'] = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
#'django.contrib.staticfiles',
'django.contrib.admin',
)
 
if not settings.configured:
settings.configure(**SETTINGS)
 
from django.db import models
from django.contrib import admin
class SomeModel(models.Model):
field_name = models.CharField(max_length=10)
 
class Meta:
app_label = this
__module__ = this
 
try:
admin.site.register(SomeModel)
except admin.sites.AlreadyRegistered:
pass
 
admin.autodiscover()
 
from django.conf.urls.defaults import patterns, url, include
from django.http import HttpResponse
def view_name(request):
out = []
for obj in SomeModel.objects.all():
out.append(obj.field_name)
 
return HttpResponse(','.join(out))
urlpatterns = patterns('',
(r'^$', view_name),
url(r'^admin/', include(admin.site.urls)),
)
 
if __name__=='__main__':
# override get_app to work with us
get_app_orig = models.get_app
def get_app(app_label,*a, **kw):
if app_label==this:
return sys.modules[__name__]
return get_app_orig(app_label, *a, **kw)
models.get_app = get_app
models.loading.cache.app_store[type(this+'.models',(),{'__file__':__file__})] = this
 
from django.core import management
management.execute_from_command_line()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.