Anonymous avatar Anonymous committed 22619fd

Works without tables, you can expressly say not to use tables, authors file, and the configuration is now stored in json.

Comments (0)

Files changed (6)

+Authors of django-helptext
+
+Jacob Smullyan - jsmullyan@gmail.com
+Dave Aaron Smith - dasmith2@gmail.com
    in managing with ``helptext`` with ``helptext.register_model()``.
 4. Edit the FieldHelp instances in the admin.  
 
+In your settings file you can specify the following:
+
+HELPTEXT_CONFIGURATION - The path to the file where you place your configured
+values should you chose to save them to a file. For example,
+'helptext_configuration.txt'.
+HELPTEXT_USE_DATABASE - Whether or not helptext should attempt to use the
+database. True or False. The default is True.
+
 Issues
 ======
 

helptext/admin.py

 from __future__ import absolute_import
 
+from django.conf import settings
 from django.contrib import admin
 
-from .models import FieldHelp
+from .models import FieldHelp, use_database
+
 
 class FieldHelpAdmin(admin.ModelAdmin):
     fields=('help_text',)
     search_fields=('field_name', 'help_text')
                 
 
-admin.site.register(FieldHelp, FieldHelpAdmin)
+if use_database():
+    admin.site.register(FieldHelp, FieldHelpAdmin)

helptext/management/commands/helptext_save.py

 from django.core.management.base import NoArgsCommand
 from helptext.models import FieldHelp
+from simplejson import dumps
+
+from ...models import get_configuration
 
 class Command(NoArgsCommand):
     help = (
-        'Loads the help text from the database and prints out a string which '
+        'Loads the help text from the configuration and database, with '
+        'priority given to the database, and prints out a json string which '
         'can be saved to a configuration file. Help text will then be the '
         'value from the database if there is one, followed by the value from '
         'configuration if there is on, finally followed by the programmed '
         'help text.\n\nFor example, you could call\n\n'
-        './manage.py helptext_save > helptext_configuration.py\n\nThen in '
-        'settings.py you need to point HELPTEXT_CONFIGURATION to the python '
-        'path of your configruation file by doing something like this:\n\n'
-        'HELPTEXT_CONFIGURATION = \'my_program.helptext_configuration\'')
+        './manage.py helptext_save > helptext_configuration.json\n\nThen in '
+        'settings.py you need HELPTEXT_CONFIGURATION = '
+        '"helptext_configuration.json"')
 
     def handle_noargs(self, **options):
-        to_save = {}
+        to_save = get_configuration().copy()
         for help in FieldHelp.objects.all():
             if help.help_text:
                 to_save[help.lookup_key()] = help.help_text
-        print "helptext_configuration = %s" % str(to_save)
+        print dumps(to_save, indent=2)

helptext/models.py

 from django.db import models
 from django.utils.importlib import import_module
 
+from simplejson import loads
+
+
 def register_app(app_label):
     model_list = models.get_models(app_label)
     register_model(*model_list)
     return set(converter(x._meta.db_table) for x in mods).issubset(all_tables)
 
 
+def use_database():
+    has_setting = hasattr(settings, "HELPTEXT_USE_DATABASE")
+    return not has_setting or settings.HELPTEXT_USE_DATABASE
+    
+
 def register_model(*model_list):
     if not ContentType._meta.installed:
         raise ImproperlyConfigured(
             "Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting "
             "in order to use the helptext application.")
 
-    if not _is_synced(ContentType, FieldHelp):
-        # syncdb not run yet -- return silently
+    if not _is_synced(ContentType):
         return
+    use_field_help_table = use_database() and _is_synced(FieldHelp)
 
     for model in model_list:
         for mod, fields in groupby(model._meta.get_fields_with_model(),
                 not f.auto_created,
                 not isinstance(f.help_text, FieldHelpProxy),))
             for field in (f for f in fields if can_help_text(f)):
-                fh = FieldHelp.objects.filter(content_type=content_type,
-                                              field_name=field.name)
-                if fh:
-                    assert len(fh) == 1
-                    fh = fh[0]
-                    if fh.original_help_text != field.help_text:
-                        fh.original_help_text = field.help_text
-                        fh.save()
-                else:
+                fh = None
+                if use_field_help_table:
+                    fhs = FieldHelp.objects.filter(content_type=content_type,
+                                                   field_name=field.name)
+                    if fhs:
+                        assert len(fhs) == 1
+                        fh = fhs[0]
+                        if fh.original_help_text != field.help_text:
+                            fh.original_help_text = field.help_text
+                            fh.save()
+                if not fh:
                     fh = FieldHelp(content_type=content_type,
                                    field_name=field.name,
                                    help_text='',
                                    original_help_text=field.help_text)
-                    fh.save()
+                    if use_field_help_table:
+                        fh.save()
                 field.help_text = FieldHelpProxy(fh)
 
 
 class FieldHelpProxy(object):
     def __init__(self, fh):
-        self . content_type=fh.content_type
-        self . field_name=fh.field_name
+        self.original_fh = fh
+        self.content_type = fh.content_type
+        self.field_name = fh.field_name
 
     def __unicode__(self):
-        try:
-            fh = FieldHelp.objects.get(content_type=self.content_type,
-                                       field_name=self.field_name)
-            return fh.get_help_text()
-        except FieldHelp.DoesNotExist:
-            # shouldn't happen
-            return ''
+        # The database table exists if an only if the original fh has a pk.
+        if self.original_fh.pk:
+            try:
+                # Don't use the original FieldHelp in case the database changed
+                fh = FieldHelp.objects.get(content_type=self.content_type,
+                                           field_name=self.field_name)
+                return fh.get_help_text()
+            except FieldHelp.DoesNotExist:
+                # shouldn't happen
+                return self.original_fh.get_non_db_help_text()
+        else:
+            return self.original_fh.get_non_db_help_text()
 
 
 _configuration = None
-def _get_configuration():
+def get_configuration():
     global _configuration
-    if None == _configuration:
+    if _configuration is None:
         if hasattr(settings, 'HELPTEXT_CONFIGURATION'):
             path = settings.HELPTEXT_CONFIGURATION
-            try:
-                mod = import_module(path)
-            except ImportError, e:
-                str = 'Error importing helptext configuration %s: "%s"'
-                raise ImproperlyConfigured(str % (path, e))
-            try:
-                helptext_configuration = mod.helptext_configuration
-            except AttributeError:
-                str = ("%s should contain a dictionary called "
-                       "helptext_configuration.")
-                raise ImproperlyConfigured(str % path)
+            f = open(path, "r")
+            helptext_configuration = loads(f.read())
+            f.close()
             if not isinstance(helptext_configuration, dict):
-                str = "%s.helptext_configuration should be a dictionary."
+                str = "%s should consist of a single json hashtable."
                 raise ImproperlyConfigured(str % path)
             _configuration = helptext_configuration
         else:
     original_help_text = models.TextField(blank=True)
 
     def get_help_text(self):
-        configured = self.get_configured_help_text()
-        return self.help_text or configured or self.original_help_text
+        return self.help_text or self.get_non_db_help_text()
 
+    def get_non_db_help_text(self):
+        return self.get_configured_help_text() or self.original_help_text
+        
     def get_configured_help_text(self):
-        helptext_configuration = _get_configuration()
+        helptext_configuration = get_configuration()
         if _configuration:
             return helptext_configuration.get(self.lookup_key(), "")
         return ""
       keywords="django help admin",
       package_dir={'' : '.'},
       packages=("helptext",),
+      requires=("simplejson>=2.0.9",),
       classifiers=['Development Status :: 3 - Alpha',
                    'Environment :: Web Environment',
                    'Framework :: Django',
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.