Move helpers/forms_helpers.py to helper/forms.py.
authorTodd Larsen <tlarsen@google.com>
Fri, 03 Oct 2008 23:59:49 +0000
changeset 274 56e1c1721299
parent 273 b97d08ebac0e
child 275 78fd8c2ed80a
Move helpers/forms_helpers.py to helper/forms.py. Patch by: Todd Larsen Review by: to-be-reviewed
app/soc/models/base.py
app/soc/views/helper/forms.py
app/soc/views/helper/lists.py
app/soc/views/helper/widgets.py
app/soc/views/helpers/forms_helpers.py
app/soc/views/person/profile.py
app/soc/views/site/docs/edit.py
app/soc/views/site/home.py
app/soc/views/site/sponsor/profile.py
app/soc/views/site/user/profile.py
app/soc/views/user/profile.py
--- a/app/soc/models/base.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/models/base.py	Fri Oct 03 23:59:49 2008 +0000
@@ -27,7 +27,8 @@
 
 from google.appengine.ext import db
 
-from soc.views.helpers import forms_helpers
+from soc.views import helper
+import soc.views.helper.forms
 
 
 class ModelWithFieldAttributes(db.Model):
@@ -69,7 +70,7 @@
       Property itself via the Model entity.
     """
     if not cls._fields_cache or (cls != cls._fields_cache.__class__.Meta.model):
-      class FieldsProxy(forms_helpers.DbModelForm):
+      class FieldsProxy(helper.forms.DbModelForm):
         """Form used as a proxy to access User model properties attributes.
         """
       
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/app/soc/views/helper/forms.py	Fri Oct 03 23:59:49 2008 +0000
@@ -0,0 +1,172 @@
+#!/usr/bin/python2.5
+#
+# Copyright 2008 the Melange authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Helpers used to display various views that are forms.
+"""
+
+__authors__ = [
+  '"Chen Lunpeng" <forever.clp@gmail.com>',
+  '"Todd Larsen" <tlarsen@google.com>',
+  ]
+
+
+from google.appengine.ext.db import djangoforms
+
+from django import newforms as forms
+from django.utils import safestring
+
+
+class DbModelForm(djangoforms.ModelForm):
+  """Subclass of Django ModelForm that fixes some label and help_text issues.
+
+  The default behavior of ModelForm is to use the verbose_name in all
+  lowercase, capitalizing only the first character, as the displayed field
+  label.  This class uses verbose_name unaltered as the visible field label
+  instead.
+
+  The Property classes used by the App Engine Datastore do not have a
+  help_text parameter to their constructor.  In a Model class, a help_text
+  attribute *can* be added to the property after it is created, but the
+  help text will not be automatically passed along to the Django ModelForm.
+  This class detects the presence of a help_text attribute and adds it to
+  the corresponding form field object.
+
+  ugettext_lazy() proxies used for internationalization in the Model will
+  still work correctly with this new behavior, as long as the original
+  strings are used as the translation keys.
+  """
+
+  def __init__(self, *args, **kwargs):
+    """Fixes label and help_text issues after parent initialization.
+
+    Args:
+      *args, **kwargs:  passed through to parent __init__() constructor
+    """
+    super(DbModelForm, self).__init__(*args, **kwargs)
+
+    for field_name in self.fields.iterkeys():
+      # Since fields can be added only to the ModelForm subclass, check to
+      # see if the Model has a corresponding field first.
+      if hasattr(self.Meta.model, field_name):
+        model_prop = getattr(self.Meta.model, field_name)
+
+        # Check if the Model property defined verbose_name, and copy that
+        # verbatim to the corresponding field label.
+        if hasattr(model_prop, 'verbose_name'):
+          self.fields[field_name].label = model_prop.verbose_name
+
+        # Check if the Model property added help_text, and copy that verbatim
+        # to the corresponding field help_text.
+        if hasattr(model_prop, 'help_text'):
+          self.fields[field_name].help_text = model_prop.help_text
+
+
+class SelectQueryArgForm(forms.Form):
+  """URL query argument change control implemented as a Django form.
+  """
+
+  ONCHANGE_JAVASCRIPT_FMT = '''
+<script type="text/javascript"> 
+  function changeArg_%(arg_name)s(item) 
+  {
+    var idx=item.selectedIndex;
+    item.selected=true;
+    var value=item.value 
+    var url = location.href 
+    var reg = /%(arg_name)s=\d+/ 
+    url = url.replace(reg, "%(arg_name)s="+value) 
+    if(url.match(reg))
+      document.location.href = url 
+   else
+      document.location.href = "%(page_path)s?%(arg_name)s="+value; 
+  }
+</script>
+'''
+
+  def __init__(self, page_path, arg_name, choices, field_name,
+               *form_args, **form_kwargs):
+    """
+    Args:
+      page_path: (usually request.path)
+      arg_name: the URL query parameter that determines which choice is
+        selected in the selection control
+      choices: list (or tuple) of value/label string two-tuples, for example:
+        (('10', '10 items per page'), ('25', '25 items per page'))
+      field_name: name of the selection field in the form
+      *form_args: positional arguments passed on to the Form base
+        class __init__()
+      *form_kwargs: keyword arguments passed on to the Form base
+        class __init__()
+    """
+    super(SelectQueryArgForm, self).__init__(*form_args, **form_kwargs)
+    
+    self._script = safestring.mark_safe(self.ONCHANGE_JAVASCRIPT_FMT % {
+        'arg_name': arg_name, 'page_path': page_path,})
+ 
+    onchange_js_call = 'changeArg_%s(this)' % arg_name
+    
+    self.fields[field_name] = forms.ChoiceField(
+        label='', choices=choices,
+        widget=forms.widgets.Select(attrs={'onchange': onchange_js_call}))
+      
+  def as_table(self):
+    """Returns form rendered as HTML <tr> rows -- with no <table></table>.
+    
+    Prepends <script> section with onchange function included.
+    """
+    return self._script + super(SelectQueryArgForm, self).as_table()
+
+  def as_ul(self):
+    """Returns form rendered as HTML <li> list items -- with no <ul></ul>.
+    
+    Prepends <script> section with onchange function included.
+    """
+    return self._script + super(SelectQueryArgForm, self).as_ul()
+
+  def as_p(self):
+    """Returns form rendered as HTML <p> paragraphs.
+    
+    Prepends <script> section with onchange function included.
+    """
+    return self._script + super(SelectQueryArgForm, self).as_p()
+
+
+DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT = 'select_query_arg_%(arg_name)s'
+
+def makeSelectQueryArgForm(
+    request, arg_name, initial_value, choices,
+    field_name_fmt=DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT):
+  """Wrapper that creates a customized SelectQueryArgForm.
+
+  Args:
+    request: the standard Django HTTP request object
+    arg_name: the URL query parameter that determines which choice is
+      selected in the selection control
+    initial_value: the initial value of the selection control
+    choices: list (or tuple) of value/label string two-tuples, for example:
+      (('10', '10 items per page'), ('25', '25 items per page'))
+    field_name_fmt: optional form field name format string; default is
+      DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT; contains these named format
+      specifiers:
+        arg_name: replaced with the arg_name argument
+
+  Returns:
+    a Django form implementing a query argument selection control, for
+    insertion into a template
+  """
+  field_name = field_name_fmt % {'arg_name': arg_name}
+  return SelectQueryArgForm(request.path, arg_name, choices, field_name,
+                            initial={field_name: initial_value})
--- a/app/soc/views/helper/lists.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/helper/lists.py	Fri Oct 03 23:59:49 2008 +0000
@@ -23,7 +23,8 @@
   ]
 
 
-from soc.views.helpers import forms_helpers
+from soc.views import helper
+import soc.views.helper.forms
 
 
 DEF_PAGINATION = 10
@@ -153,20 +154,20 @@
 
 def makePaginationForm(
   request, limit, arg_name='limit', choices=DEF_PAGINATION_CHOICES,
-  field_name_fmt=forms_helpers.DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT):
+  field_name_fmt=helper.forms.DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT):
   """Returns a customized pagination limit selection form.
   
   Args:
     request: the standard Django HTTP request object
     limit: the initial value of the selection control
-    arg_name: see forms_helpers.makeSelectQueryArgForm(); default is 'limit'
-    choices: see forms_helpers.makeSelectQueryArgForm(); default is
+    arg_name: see helper.forms.makeSelectQueryArgForm(); default is 'limit'
+    choices: see helper.forms.makeSelectQueryArgForm(); default is
       DEF_PAGINATION_CHOICES
-    field_name_fmt: see forms_helpers.makeSelectQueryArgForm()
+    field_name_fmt: see helper.forms.makeSelectQueryArgForm()
   """
   choices = makeNewPaginationChoices(limit=limit, choices=choices)
   
-  return forms_helpers.makeSelectQueryArgForm(
+  return helper.forms.makeSelectQueryArgForm(
       request, arg_name, limit, choices)
 
 
@@ -177,7 +178,7 @@
   Args:
     limit: the initial value of the selection control;
       default is DEF_PAGINATION
-    choices: see forms_helpers.makeSelectQueryArgForm();
+    choices: see helper.forms.makeSelectQueryArgForm();
       default is DEF_PAGINATION_CHOICES
 
   Returns:
--- a/app/soc/views/helper/widgets.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/helper/widgets.py	Fri Oct 03 23:59:49 2008 +0000
@@ -52,7 +52,7 @@
   dictionary
 
   You can set TinyMCE widget for particular form field using code below:
-    class ExampleForm(forms_helpers.DbModelForm):
+    class ExampleForm(helper.forms.DbModelForm):
       content = forms.fields.CharField(widget=helper.widgets.TinyMCE())
   
   You can include tiny_mce_src.js in your template using:
--- a/app/soc/views/helpers/forms_helpers.py	Fri Oct 03 23:24:12 2008 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,172 +0,0 @@
-#!/usr/bin/python2.5
-#
-# Copyright 2008 the Melange authors.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-#   http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-"""Helpers used to display various views that are forms.
-"""
-
-__authors__ = [
-  '"Chen Lunpeng" <forever.clp@gmail.com>',
-  '"Todd Larsen" <tlarsen@google.com>',
-  ]
-
-
-from google.appengine.ext.db import djangoforms
-
-from django import newforms as forms
-from django.utils import safestring
-
-
-class DbModelForm(djangoforms.ModelForm):
-  """Subclass of Django ModelForm that fixes some label and help_text issues.
-
-  The default behavior of ModelForm is to use the verbose_name in all
-  lowercase, capitalizing only the first character, as the displayed field
-  label.  This class uses verbose_name unaltered as the visible field label
-  instead.
-
-  The Property classes used by the App Engine Datastore do not have a
-  help_text parameter to their constructor.  In a Model class, a help_text
-  attribute *can* be added to the property after it is created, but the
-  help text will not be automatically passed along to the Django ModelForm.
-  This class detects the presence of a help_text attribute and adds it to
-  the corresponding form field object.
-
-  ugettext_lazy() proxies used for internationalization in the Model will
-  still work correctly with this new behavior, as long as the original
-  strings are used as the translation keys.
-  """
-
-  def __init__(self, *args, **kwargs):
-    """Fixes label and help_text issues after parent initialization.
-
-    Args:
-      *args, **kwargs:  passed through to parent __init__() constructor
-    """
-    super(DbModelForm, self).__init__(*args, **kwargs)
-
-    for field_name in self.fields.iterkeys():
-      # Since fields can be added only to the ModelForm subclass, check to
-      # see if the Model has a corresponding field first.
-      if hasattr(self.Meta.model, field_name):
-        model_prop = getattr(self.Meta.model, field_name)
-
-        # Check if the Model property defined verbose_name, and copy that
-        # verbatim to the corresponding field label.
-        if hasattr(model_prop, 'verbose_name'):
-          self.fields[field_name].label = model_prop.verbose_name
-
-        # Check if the Model property added help_text, and copy that verbatim
-        # to the corresponding field help_text.
-        if hasattr(model_prop, 'help_text'):
-          self.fields[field_name].help_text = model_prop.help_text
-
-
-class SelectQueryArgForm(forms.Form):
-  """URL query argument change control implemented as a Django form.
-  """
-
-  ONCHANGE_JAVASCRIPT_FMT = '''
-<script type="text/javascript"> 
-  function changeArg_%(arg_name)s(item) 
-  {
-    var idx=item.selectedIndex;
-    item.selected=true;
-    var value=item.value 
-    var url = location.href 
-    var reg = /%(arg_name)s=\d+/ 
-    url = url.replace(reg, "%(arg_name)s="+value) 
-    if(url.match(reg))
-      document.location.href = url 
-   else
-      document.location.href = "%(page_path)s?%(arg_name)s="+value; 
-  }
-</script>
-'''
-
-  def __init__(self, page_path, arg_name, choices, field_name,
-               *form_args, **form_kwargs):
-    """
-    Args:
-      page_path: (usually request.path)
-      arg_name: the URL query parameter that determines which choice is
-        selected in the selection control
-      choices: list (or tuple) of value/label string two-tuples, for example:
-        (('10', '10 items per page'), ('25', '25 items per page'))
-      field_name: name of the selection field in the form
-      *form_args: positional arguments passed on to the Form base
-        class __init__()
-      *form_kwargs: keyword arguments passed on to the Form base
-        class __init__()
-    """
-    super(SelectQueryArgForm, self).__init__(*form_args, **form_kwargs)
-    
-    self._script = safestring.mark_safe(self.ONCHANGE_JAVASCRIPT_FMT % {
-        'arg_name': arg_name, 'page_path': page_path,})
- 
-    onchange_js_call = 'changeArg_%s(this)' % arg_name
-    
-    self.fields[field_name] = forms.ChoiceField(
-        label='', choices=choices,
-        widget=forms.widgets.Select(attrs={'onchange': onchange_js_call}))
-      
-  def as_table(self):
-    """Returns form rendered as HTML <tr> rows -- with no <table></table>.
-    
-    Prepends <script> section with onchange function included.
-    """
-    return self._script + super(SelectQueryArgForm, self).as_table()
-
-  def as_ul(self):
-    """Returns form rendered as HTML <li> list items -- with no <ul></ul>.
-    
-    Prepends <script> section with onchange function included.
-    """
-    return self._script + super(SelectQueryArgForm, self).as_ul()
-
-  def as_p(self):
-    """Returns form rendered as HTML <p> paragraphs.
-    
-    Prepends <script> section with onchange function included.
-    """
-    return self._script + super(SelectQueryArgForm, self).as_p()
-
-
-DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT = 'select_query_arg_%(arg_name)s'
-
-def makeSelectQueryArgForm(
-    request, arg_name, initial_value, choices,
-    field_name_fmt=DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT):
-  """Wrapper that creates a customized SelectQueryArgForm.
-
-  Args:
-    request: the standard Django HTTP request object
-    arg_name: the URL query parameter that determines which choice is
-      selected in the selection control
-    initial_value: the initial value of the selection control
-    choices: list (or tuple) of value/label string two-tuples, for example:
-      (('10', '10 items per page'), ('25', '25 items per page'))
-    field_name_fmt: optional form field name format string; default is
-      DEF_SELECT_QUERY_ARG_FIELD_NAME_FMT; contains these named format
-      specifiers:
-        arg_name: replaced with the arg_name argument
-
-  Returns:
-    a Django form implementing a query argument selection control, for
-    insertion into a template
-  """
-  field_name = field_name_fmt % {'arg_name': arg_name}
-  return SelectQueryArgForm(request.path, arg_name, choices, field_name,
-                            initial={field_name: initial_value})
--- a/app/soc/views/person/profile.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/person/profile.py	Fri Oct 03 23:59:49 2008 +0000
@@ -34,10 +34,11 @@
 from django import newforms as forms
 
 from soc.models import person
-from soc.views.helpers import forms_helpers
+from soc.views import helper
+import soc.views.helper.forms
 
 
-class EditForm(forms_helpers.DbModelForm):
+class EditForm(helper.forms.DbModelForm):
   """Django form displayed when creating or editing a Person.
   """
 
--- a/app/soc/views/site/docs/edit.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/site/docs/edit.py	Fri Oct 03 23:59:49 2008 +0000
@@ -33,17 +33,17 @@
 from soc.logic import path_linkname
 from soc.logic.site import id_user
 from soc.views import helper
+import soc.views.helper.forms
 import soc.views.helper.requests
 import soc.views.helper.responses
 import soc.views.helper.widgets
 from soc.views import simple
-from soc.views.helpers import forms_helpers
 from soc.views.user import profile
 
 import soc.models.document
 
 
-class EditForm(forms_helpers.DbModelForm):
+class EditForm(helper.forms.DbModelForm):
   """Django form displayed when Developer edits a Document.
   """
   doc_key_name = forms.CharField(widget=forms.HiddenInput)
@@ -202,7 +202,7 @@
   return helper.responses.respond(request, template, context)
 
 
-class CreateForm(forms_helpers.DbModelForm):
+class CreateForm(helper.forms.DbModelForm):
   """Django form displayed when Developer creates a Document.
   """
   doc_key_name = forms.CharField(widget=forms.HiddenInput)
--- a/app/soc/views/site/home.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/site/home.py	Fri Oct 03 23:59:49 2008 +0000
@@ -38,10 +38,10 @@
 from soc.logic.site import id_user
 from soc.views import simple
 from soc.views import helper
+import soc.views.helper.forms
 import soc.views.helper.responses
 import soc.views.helper.templates
 import soc.views.helper.widgets
-from soc.views.helpers import forms_helpers
 
 import soc.models.site_settings
 import soc.models.document
@@ -49,7 +49,7 @@
 import soc.logic.site.settings
 
 
-class DocumentForm(forms_helpers.DbModelForm):
+class DocumentForm(helper.forms.DbModelForm):
   content = forms.fields.CharField(widget=helper.widgets.TinyMCE())
 
   class Meta:
@@ -63,7 +63,7 @@
                'user', 'modified', 'created', 'inheritance_line']
 
 
-class SiteSettingsForm(forms_helpers.DbModelForm):
+class SiteSettingsForm(helper.forms.DbModelForm):
   """Django form displayed when creating or editing Site Settings.
   """
   class Meta:
--- a/app/soc/views/site/sponsor/profile.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/site/sponsor/profile.py	Fri Oct 03 23:59:49 2008 +0000
@@ -32,17 +32,17 @@
 from soc.logic import sponsor
 from soc.logic.site import id_user
 from soc.views import helper
+import soc.views.helper.forms
 import soc.views.helper.requests
 import soc.views.helper.responses
 import soc.views.helper.widgets
 from soc.views import simple
-from soc.views.helpers import forms_helpers
 from soc.views.user import profile
 
 import soc.models.sponsor
 
 
-class CreateForm(forms_helpers.DbModelForm):
+class CreateForm(helper.forms.DbModelForm):
   """Django form displayed when creating a Sponsor.
   """
   class Meta:
--- a/app/soc/views/site/user/profile.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/site/user/profile.py	Fri Oct 03 23:59:49 2008 +0000
@@ -33,16 +33,16 @@
 from soc.logic.site import id_user
 from soc.views import simple
 from soc.views import helper
+import soc.views.helper.forms
 import soc.views.helper.lists
 import soc.views.helper.requests
 import soc.views.helper.responses
-from soc.views.helpers import forms_helpers
 from soc.views.user import profile
 
 import soc.models.user
 
 
-class LookupForm(forms_helpers.DbModelForm):
+class LookupForm(helper.forms.DbModelForm):
   """Django form displayed for a Developer to look up a User.
   
   This form is manually specified, instead of using
@@ -184,7 +184,7 @@
   return helper.responses.respond(request, template, context)
 
 
-class EditForm(forms_helpers.DbModelForm):
+class EditForm(helper.forms.DbModelForm):
   """Django form displayed when Developer edits a User.
   
   This form is manually specified, instead of using
@@ -334,7 +334,7 @@
   return helper.responses.respond(request, template, context)
 
 
-class CreateForm(forms_helpers.DbModelForm):
+class CreateForm(helper.forms.DbModelForm):
   """Django form displayed when Developer creates a User.
 
   This form is manually specified, instead of using
--- a/app/soc/views/user/profile.py	Fri Oct 03 23:24:12 2008 +0000
+++ b/app/soc/views/user/profile.py	Fri Oct 03 23:59:49 2008 +0000
@@ -32,15 +32,15 @@
 from soc.logic import out_of_band
 from soc.logic.site import id_user
 from soc.views import helper
+import soc.views.helper.forms
 import soc.views.helper.requests
 import soc.views.helper.responses
 from soc.views import simple
-from soc.views.helpers import forms_helpers
 
 import soc.models.user
 
 
-class UserForm(forms_helpers.DbModelForm):
+class UserForm(helper.forms.DbModelForm):
   """Django form displayed when creating or editing a User.
   """
   class Meta: