Browse Source

Added a django admin command to list fieldtypes

Yann Weber 9 years ago
parent
commit
2b6615775c

+ 14
- 32
EditorialModel/fields.py View File

@@ -5,6 +5,7 @@ import importlib
5 5
 from EditorialModel.components import EmComponent
6 6
 from EditorialModel.exceptions import EmComponentCheckError
7 7
 import EditorialModel
8
+import EditorialModel.fieldtypes
8 9
 from django.db import models
9 10
 
10 11
 ## EmField (Class)
@@ -15,28 +16,16 @@ class EmField(EmComponent):
15 16
     ranked_in = 'fieldgroup_id'
16 17
 
17 18
     ftype = None
18
-
19
-    fieldtypes = {
20
-        'int': models.IntegerField,
21
-        'integer': models.IntegerField,
22
-        'bigint': models.BigIntegerField,
23
-        'smallint': models.SmallIntegerField,
24
-        'boolean': models.BooleanField,
25
-        'bool': models.BooleanField,
26
-        'float': models.FloatField,
27
-        'char': models.CharField,
28
-        'varchar': models.CharField,
29
-        'text': models.TextField,
30
-        'time': models.TimeField,
31
-        'date': models.DateField,
32
-        'datetime': models.DateTimeField,
33
-    }
19
+    help = 'Default help text'
34 20
 
35 21
     ## Instanciate a new EmField
36 22
     # @todo define and test type for icon and fieldtype
37 23
     # @warning nullable == True by default
38 24
     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):
39 25
 
26
+        if self.ftype == None:
27
+            raise NotImplementedError("Trying to instanciate an EmField and not one of the fieldtypes child classes")
28
+
40 29
         self.fieldgroup_id = fieldgroup_id
41 30
         self.check_type('fieldgroup_id', int)
42 31
         self.optional = optional
@@ -57,10 +46,19 @@ class EmField(EmComponent):
57 46
         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)
58 47
 
59 48
     @staticmethod
49
+    ## @brief Return an EmField subclass given a wanted field type
50
+    # @return An EmField subclass
51
+    # @throw When not found
52
+    # @see EmField::fieldtypes()
60 53
     def get_field_class(ftype, **kwargs):
61 54
         ftype_module = importlib.import_module('EditorialModel.fieldtypes.%s'%ftype)
62 55
         return ftype_module.fclass
63 56
 
57
+    @staticmethod
58
+    ## @brief Return the list of allowed field type
59
+    def fieldtypes_list():
60
+        return [ f for f in EditorialModel.fieldtypes.__all__ if f != '__init__' ]
61
+
64 62
     ## @brief Abstract method that should return a validation function
65 63
     # @param raise_e Exception : if not valid raise this exception
66 64
     # @param ret_valid : if valid return this value
@@ -98,19 +96,3 @@ class EmField(EmComponent):
98 96
     def delete_check(self):
99 97
         return True
100 98
 
101
-    """
102
-    def to_django(self):
103
-        if self.fieldtype in ('varchar', 'char'):
104
-            max_length = None if 'max_length' not in self.options else self.options['max_length']
105
-            return self.fieldtypes[self.fieldtype](max_length=max_length, **self.options)
106
-
107
-        if self.fieldtype in ('time', 'datetime', 'date'):
108
-            auto_now = False if 'auto_now' not in self.options else self.options['auto_now']
109
-            auto_now_add = False if 'auto_now_add' not in self.options else self.options['auto_now_add']
110
-            return self.fieldtypes[self.fieldtype](auto_now=auto_now, auto_now_add=auto_now_add, **self.options)
111
-
112
-        if self.fieldtype == 'boolean' and ('nullable' in self.options and self.options['nullable'] == 1):
113
-            return models.NullBooleanField(**self.options)
114
-
115
-        return self.fieldtypes[self.fieldtype](**self.options)
116
-    """

+ 1
- 1
EditorialModel/fieldtypes/__init__.py View File

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

+ 3
- 0
EditorialModel/fieldtypes/bool.py View File

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

+ 1
- 0
EditorialModel/fieldtypes/char.py View File

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

+ 2
- 0
EditorialModel/fieldtypes/datetime.py View File

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

+ 1
- 0
EditorialModel/fieldtypes/file.py View File

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

+ 2
- 0
EditorialModel/fieldtypes/int.py View File

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

+ 3
- 1
EditorialModel/fieldtypes/regexchar.py View File

@@ -1,9 +1,11 @@
1 1
 #-*- coding: utf-8 -*-
2 2
 
3 3
 import re
4
-from EditorialModel.fieldtypes import EmFieldChar
4
+from EditorialModel.fieldtypes.char import EmFieldChar
5 5
 
6 6
 class EmFieldCharRegex(EmFieldChar):
7
+
8
+    help = 'String field validated with a regex. Take two optionss : max_length and regex'
7 9
     
8 10
     ## @brief A char field validated with a regex
9 11
     # @param regex str : a regex string (passed as argument to re.compile() )

+ 2
- 0
EditorialModel/fieldtypes/rel2type.py View File

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

+ 1
- 0
EditorialModel/fieldtypes/text.py View File

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

+ 5
- 1
EditorialModel/migrationhandler/django.py View File

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

+ 0
- 0
Lodel/management/__init__.py View File


+ 0
- 0
Lodel/management/commands/__init__.py View File


+ 22
- 0
Lodel/management/commands/listfieldtypes.py View File

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

+ 1
- 0
Lodel/settings/defaults.py View File

@@ -59,6 +59,7 @@ INSTALLED_APPS = (
59 59
     'django.contrib.messages',
60 60
     'django.contrib.staticfiles',
61 61
     'LodelTestInstance',
62
+    'Lodel',
62 63
 )
63 64
 
64 65
 MIDDLEWARE_CLASSES = (

Loading…
Cancel
Save