1
0
Fork 0
mirror of https://github.com/yweber/lodel2.git synced 2025-11-14 18:09:17 +01:00

Added a django admin command to list fieldtypes

This commit is contained in:
Yann 2015-09-17 16:24:17 +02:00
commit 2b6615775c
15 changed files with 58 additions and 35 deletions

View file

@ -5,6 +5,7 @@ import importlib
from EditorialModel.components import EmComponent from EditorialModel.components import EmComponent
from EditorialModel.exceptions import EmComponentCheckError from EditorialModel.exceptions import EmComponentCheckError
import EditorialModel import EditorialModel
import EditorialModel.fieldtypes
from django.db import models from django.db import models
## EmField (Class) ## EmField (Class)
@ -15,28 +16,16 @@ class EmField(EmComponent):
ranked_in = 'fieldgroup_id' ranked_in = 'fieldgroup_id'
ftype = None ftype = None
help = 'Default help text'
fieldtypes = {
'int': models.IntegerField,
'integer': models.IntegerField,
'bigint': models.BigIntegerField,
'smallint': models.SmallIntegerField,
'boolean': models.BooleanField,
'bool': models.BooleanField,
'float': models.FloatField,
'char': models.CharField,
'varchar': models.CharField,
'text': models.TextField,
'time': models.TimeField,
'date': models.DateField,
'datetime': models.DateTimeField,
}
## Instanciate a new EmField ## Instanciate a new EmField
# @todo define and test type for icon and fieldtype # @todo define and test type for icon and fieldtype
# @warning nullable == True by default # @warning nullable == True by default
def __init__(self, model, uid, name, fieldgroup_id, optional=False, internal=False, rel_field_id=None, icon='0', string=None, help_text=None, date_update=None, date_create=None, rank=None, nullable = True, default = None, uniq = False, **kwargs): def __init__(self, model, uid, name, fieldgroup_id, optional=False, internal=False, rel_field_id=None, icon='0', string=None, help_text=None, date_update=None, date_create=None, rank=None, nullable = True, default = None, uniq = False, **kwargs):
if self.ftype == None:
raise NotImplementedError("Trying to instanciate an EmField and not one of the fieldtypes child classes")
self.fieldgroup_id = fieldgroup_id self.fieldgroup_id = fieldgroup_id
self.check_type('fieldgroup_id', int) self.check_type('fieldgroup_id', int)
self.optional = optional self.optional = optional
@ -57,10 +46,19 @@ class EmField(EmComponent):
super(EmField, self).__init__(model=model, uid=uid, name=name, string=string, help_text=help_text, date_update=date_update, date_create=date_create, rank=rank) super(EmField, self).__init__(model=model, uid=uid, name=name, string=string, help_text=help_text, date_update=date_update, date_create=date_create, rank=rank)
@staticmethod @staticmethod
## @brief Return an EmField subclass given a wanted field type
# @return An EmField subclass
# @throw When not found
# @see EmField::fieldtypes()
def get_field_class(ftype, **kwargs): def get_field_class(ftype, **kwargs):
ftype_module = importlib.import_module('EditorialModel.fieldtypes.%s'%ftype) ftype_module = importlib.import_module('EditorialModel.fieldtypes.%s'%ftype)
return ftype_module.fclass return ftype_module.fclass
@staticmethod
## @brief Return the list of allowed field type
def fieldtypes_list():
return [ f for f in EditorialModel.fieldtypes.__all__ if f != '__init__' ]
## @brief Abstract method that should return a validation function ## @brief Abstract method that should return a validation function
# @param raise_e Exception : if not valid raise this exception # @param raise_e Exception : if not valid raise this exception
# @param ret_valid : if valid return this value # @param ret_valid : if valid return this value
@ -98,19 +96,3 @@ class EmField(EmComponent):
def delete_check(self): def delete_check(self):
return True return True
"""
def to_django(self):
if self.fieldtype in ('varchar', 'char'):
max_length = None if 'max_length' not in self.options else self.options['max_length']
return self.fieldtypes[self.fieldtype](max_length=max_length, **self.options)
if self.fieldtype in ('time', 'datetime', 'date'):
auto_now = False if 'auto_now' not in self.options else self.options['auto_now']
auto_now_add = False if 'auto_now_add' not in self.options else self.options['auto_now_add']
return self.fieldtypes[self.fieldtype](auto_now=auto_now, auto_now_add=auto_now_add, **self.options)
if self.fieldtype == 'boolean' and ('nullable' in self.options and self.options['nullable'] == 1):
return models.NullBooleanField(**self.options)
return self.fieldtypes[self.fieldtype](**self.options)
"""

View file

@ -1,5 +1,5 @@
from os.path import dirname, basename, isfile from os.path import dirname, basename, isfile
import glob import glob
modules = glob.glob(dirname(__file__)+"/*.py") modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and f != '__init__.py'] __all__ = [ basename(f)[:-3] for f in modules if isfile(f) and basename(f) != '__init__.py']

View file

@ -5,8 +5,11 @@ from EditorialModel.fields import EmField
class EmFieldBool(EmField): class EmFieldBool(EmField):
ftype = 'bool' ftype = 'bool'
help = 'A basic boolean field'
## @brief A char field ## @brief A char field
# @brief max_length int : The maximum length of this field # @brief max_length int : The maximum length of this field
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(EmFieldChar, self).__init__(**kwargs) super(EmFieldChar, self).__init__(**kwargs)
fclass=EmFieldBool

View file

@ -5,6 +5,7 @@ from EditorialModel.fields import EmField
class EmFieldChar(EmField): class EmFieldChar(EmField):
ftype = 'char' ftype = 'char'
help = 'Basic string (varchar) field. Take max_length=64 as option'
## @brief A char field ## @brief A char field
# @brief max_length int : The maximum length of this field # @brief max_length int : The maximum length of this field

View file

@ -6,6 +6,8 @@ class EmFieldDatetime(EmField):
ftype = 'datetime' ftype = 'datetime'
help = 'A datetime field. Take two boolean options now_on_update and now_on_create'
## @brief A datetime field ## @brief A datetime field
# @param now_on_update bool : If true the date is set to NOW on update # @param now_on_update bool : If true the date is set to NOW on update
# @param now_on_create bool : If true the date is set to NEW on creation # @param now_on_create bool : If true the date is set to NEW on creation

View file

@ -5,6 +5,7 @@ from EditorialModel.fields import EmField
class EmFieldFile(EmField): class EmFieldFile(EmField):
ftype = 'file' ftype = 'file'
help = 'A file field. With one options upload_path'
## @brief A char field ## @brief A char field
# @brief max_length int : The maximum length of this field # @brief max_length int : The maximum length of this field

View file

@ -7,6 +7,8 @@ class EmFieldInt(EmField):
ftype = 'int' ftype = 'int'
help = 'Basic integer field'
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(EmFieldChar, self).__init__(**kwargs) super(EmFieldChar, self).__init__(**kwargs)

View file

@ -1,10 +1,12 @@
#-*- coding: utf-8 -*- #-*- coding: utf-8 -*-
import re import re
from EditorialModel.fieldtypes import EmFieldChar from EditorialModel.fieldtypes.char import EmFieldChar
class EmFieldCharRegex(EmFieldChar): class EmFieldCharRegex(EmFieldChar):
help = 'String field validated with a regex. Take two optionss : max_length and regex'
## @brief A char field validated with a regex ## @brief A char field validated with a regex
# @param regex str : a regex string (passed as argument to re.compile() ) # @param regex str : a regex string (passed as argument to re.compile() )
# @param max_length int : the maximum length for this field # @param max_length int : the maximum length for this field

View file

@ -6,6 +6,8 @@ class EmFieldRel2Type(EmField):
ftype= 'rel2type' ftype= 'rel2type'
help = 'Relationnal field (relation2type). Take rel_to_type_id as option (an EmType uid)'
def __init__(self, rel_to_type_id, **kwargs): def __init__(self, rel_to_type_id, **kwargs):
self.rel_to_type_id = rel_to_type_id self.rel_to_type_id = rel_to_type_id
super(EmFieldRel2Type, self).__init__(**kwargs) super(EmFieldRel2Type, self).__init__(**kwargs)

View file

@ -5,6 +5,7 @@ from EditorialModel.fields import EmField
class EmFieldText(EmField): class EmFieldText(EmField):
ftype = 'text' ftype = 'text'
help = 'A text field (big string)'
def __init__(self, **kwargs): def __init__(self, **kwargs):
super(EmFieldText, self).__init__(**kwargs) super(EmFieldText, self).__init__(**kwargs)

View file

@ -305,6 +305,11 @@ class DjangoMigrationHandler(object):
args['auto_now'] = f.now_on_update args['auto_now'] = f.now_on_update
args['auto_now_add'] = f.now_on_create args['auto_now_add'] = f.now_on_create
return models.DateTimeField(**args) return models.DateTimeField(**args)
elif f.ftype == 'bool': #Boolean field
if args['null']:
return models.NullBooleanField(**args)
del(args['null'])
return models.BooleanField(**args)
elif f.ftype == 'rel2type': #Relation to type elif f.ftype == 'rel2type': #Relation to type
if assoc_comp == None: if assoc_comp == None:
@ -331,7 +336,6 @@ class DjangoMigrationHandler(object):
through_model = create_model(through_model_name, through_fields, self.app_name, module_name) through_model = create_model(through_model_name, through_fields, self.app_name, module_name)
kwargs['through'] = through_model_name kwargs['through'] = through_model_name
print('WOW !')
return models.ManyToManyField(f.get_related_type().uniq_name, **kwargs) return models.ManyToManyField(f.get_related_type().uniq_name, **kwargs)
else: else:
raise NotImplemented("The conversion to django fields is not yet implemented for %s field type"%f.ftype) raise NotImplemented("The conversion to django fields is not yet implemented for %s field type"%f.ftype)

View file

View file

View file

@ -0,0 +1,22 @@
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from EditorialModel.fields import EmField
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--silent',
action='store_true',
dest='silent',
default=False,
help='Only display field types name and hide the help text'),
)
help = 'List all the possible field types'
def handle(self, *args, **options):
if options['silent']:
for ftype in EmField.fieldtypes_list():
self.stdout.write("\t%s\n"%ftype)
else:
self.stdout.write("Field types list : ")
for ftype in EmField.fieldtypes_list():
self.stdout.write("\t{0:15} {1}".format(ftype, EmField.get_field_class(ftype).help))

View file

@ -59,6 +59,7 @@ INSTALLED_APPS = (
'django.contrib.messages', 'django.contrib.messages',
'django.contrib.staticfiles', 'django.contrib.staticfiles',
'LodelTestInstance', 'LodelTestInstance',
'Lodel',
) )
MIDDLEWARE_CLASSES = ( MIDDLEWARE_CLASSES = (