1. Gustavo Picon
  2. django-treebeard

Commits

Gustavo Picon  committed b5bd043

Pep8fication

  • Participants
  • Parent commits 283a635
  • Branches default

Comments (0)

Files changed (6)

File docs/conf.py

View file
 # -*- coding: utf-8 -*-
-#
-# django-treebeard documentation build configuration file, created by
-# sphinx-quickstart on Tue Apr 13 01:06:14 2010.
-#
-# This file is execfile()d with the current directory set to its containing dir.
-#
-# Note that not all possible configuration values are present in this
-# autogenerated file.
-#
-# All configuration values have a default; values that are commented out
-# serve to show the default.
+"""
 
-import sys, os
+Configuration for the Sphinx documentation generator.
 
-# If extensions (or modules to document with autodoc) are in another directory,
-# add these directories to sys.path here. If the directory is relative to the
-# documentation root, use os.path.abspath to make it absolute, like shown here.
-#sys.path.append(os.path.abspath('.'))
+Reference: http://sphinx.pocoo.org/config.html
+
+"""
+
+import os
+import sys
 sys.path.append(os.path.abspath('..'))
 os.environ['DJANGO_SETTINGS_MODULE'] = 'django.conf.global_settings'
-
-# -- General configuration -----------------------------------------------------
-
-# Add any Sphinx extension module names here, as strings. They can be extensions
-# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
 extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage',
               'sphinx.ext.graphviz', 'sphinx.ext.inheritance_diagram',
               'sphinx.ext.todo']
-
-# Add any paths that contain templates here, relative to this directory.
 templates_path = ['_templates']
-
-# The suffix of source filenames.
 source_suffix = '.rst'
-
-# The encoding of source files.
-#source_encoding = 'utf-8'
-
-# The master toctree document.
 master_doc = 'index'
-
-# General information about the project.
 project = u'django-treebeard'
 copyright = u'2008-2010, Gustavo Picon'
-
-# The version info for the project you're documenting, acts as replacement for
-# |version| and |release|, also used in various other places throughout the
-# built documents.
-#
-# The short X.Y version.
 version = '2.0a1'
-# The full version, including alpha/beta/rc tags.
 release = '2.0a1'
-
-# The language for content autogenerated by Sphinx. Refer to documentation
-# for a list of supported languages.
-#language = None
-
-# There are two options for replacing |today|: either, you set today to some
-# non-false value, then it is used:
-#today = ''
-# Else, today_fmt is used as the format for a strftime call.
-#today_fmt = '%B %d, %Y'
-
-# List of documents that shouldn't be included in the build.
-#unused_docs = []
-
-# List of directories, relative to source directory, that shouldn't be searched
-# for source files.
 exclude_trees = ['_build']
-
-# The reST default role (used for this markup: `text`) to use for all documents.
-#default_role = None
-
-# If true, '()' will be appended to :func: etc. cross-reference text.
-#add_function_parentheses = True
-
-# If true, the current module name will be prepended to all description
-# unit titles (such as .. function::).
-#add_module_names = True
-
-# If true, sectionauthor and moduleauthor directives will be shown in the
-# output. They are ignored by default.
-#show_authors = False
-
-# The name of the Pygments (syntax highlighting) style to use.
 pygments_style = 'sphinx'
-
-# A list of ignored prefixes for module index sorting.
-#modindex_common_prefix = []
-
-
-# -- Options for HTML output ---------------------------------------------------
-
-# The theme to use for HTML and HTML Help pages.  Major themes that come with
-# Sphinx are currently 'default' and 'sphinxdoc'.
 html_theme = 'default'
-
-# Theme options are theme-specific and customize the look and feel of a theme
-# further.  For a list of options available for each theme, see the
-# documentation.
-#html_theme_options = {}
-
-# Add any paths that contain custom themes here, relative to this directory.
-#html_theme_path = []
-
-# The name for this set of Sphinx documents.  If None, it defaults to
-# "<project> v<release> documentation".
-#html_title = None
-
-# A shorter title for the navigation bar.  Default is the same as html_title.
-#html_short_title = None
-
-# The name of an image file (relative to this directory) to place at the top
-# of the sidebar.
-#html_logo = None
-
-# The name of an image file (within the static path) to use as favicon of the
-# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
-# pixels large.
-#html_favicon = None
-
-# Add any paths that contain custom static files (such as style sheets) here,
-# relative to this directory. They are copied after the builtin static files,
-# so a file named "default.css" will overwrite the builtin "default.css".
 html_static_path = ['_static']
-
-# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
-# using the given strftime format.
-#html_last_updated_fmt = '%b %d, %Y'
-
-# If true, SmartyPants will be used to convert quotes and dashes to
-# typographically correct entities.
-#html_use_smartypants = True
-
-# Custom sidebar templates, maps document names to template names.
-#html_sidebars = {}
-
-# Additional templates that should be rendered to pages, maps page names to
-# template names.
-#html_additional_pages = {}
-
-# If false, no module index is generated.
-#html_use_modindex = True
-
-# If false, no index is generated.
-#html_use_index = True
-
-# If true, the index is split into individual pages for each letter.
-#html_split_index = False
-
-# If true, links to the reST sources are added to the pages.
-#html_show_sourcelink = True
-
-# If true, an OpenSearch description file will be output, and all pages will
-# contain a <link> tag referring to it.  The value of this option must be the
-# base URL from which the finished HTML is served.
-#html_use_opensearch = ''
-
-# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
-#html_file_suffix = ''
-
-# Output file base name for HTML help builder.
 htmlhelp_basename = 'django-treebearddoc'
-
-
-# -- Options for LaTeX output --------------------------------------------------
-
-# The paper size ('letter' or 'a4').
-#latex_paper_size = 'letter'
-
-# The font size ('10pt', '11pt' or '12pt').
-#latex_font_size = '10pt'
-
-# Grouping the document tree into LaTeX files. List of tuples
-# (source start file, target name, title, author, documentclass [howto/manual]).
 latex_documents = [
   ('index', 'django-treebeard.tex', u'django-treebeard Documentation',
-   u'Gustavo Picon', 'manual'),
-]
-
-# The name of an image file (relative to this directory) to place at the top of
-# the title page.
-#latex_logo = None
-
-# For "manual" documents, if this is true, then toplevel headings are parts,
-# not chapters.
-#latex_use_parts = False
-
-# Additional stuff for the LaTeX preamble.
-#latex_preamble = ''
-
-# Documents to append as an appendix to all manuals.
-#latex_appendices = []
-
-# If false, no module index is generated.
-#latex_use_modindex = True
+   u'Gustavo Picon', 'manual')]

File treebeard/admin.py

View file
 
 from treebeard.forms import MoveNodeForm
 from treebeard.templatetags.admin_tree import check_empty_dict
-from treebeard.exceptions import InvalidPosition, MissingNodeOrderBy, InvalidMoveToDescendant, PathOverflow
+from treebeard.exceptions import (InvalidPosition, MissingNodeOrderBy,
+        InvalidMoveToDescendant, PathOverflow)
+
 
 class TreeChangeList(ChangeList):
 
         from treebeard.al_tree import AL_Node
         if issubclass(self.model, AL_Node):
             # For AL trees, use the old admin display
-            self.change_list_template = 'admin/tree_list.html' 
+            self.change_list_template = 'admin/tree_list.html'
         return super(TreeAdmin, self).changelist_view(request, extra_context)
 
     def get_urls(self):
     def move_node(self, request):
         try:
             node_id = request.POST['node_id']
-            parent_id = request.POST['parent_id']
             sibling_id = request.POST['sibling_id']
             as_child = request.POST.get('as_child', False)
             as_child = bool(int(as_child))
                     node.move(sibling, pos='left')
             except InvalidPosition, e:
                 # This could be due two reasons (from the docs):
-                # :raise InvalidPosition: when passing an invalid ``pos`` parm
-                # :raise InvalidPosition: when :attr:`node_order_by` is enabled and
-                #   the``pos`` parm wasn't ``sorted-sibling`` or ``sorted-child``
-                # 
-                # If it happened because the node is not a 'sorted-sibling' or 
-                # 'sorted-child' then try to move just a child without preserving the
-                # order, so try a different move
+                # :raise InvalidPosition:
+                #       when passing an invalid ``pos`` parm
+                # :raise InvalidPosition:
+                #       when :attr:`node_order_by` is enabled and
+                #       the``pos`` parm wasn't ``sorted-sibling``
+                #       or ``sorted-child``
+                #
+                # If it happened because the node is not a 'sorted-sibling'
+                # or 'sorted-child' then try to move just a child without
+                # preserving the order, so try a different move
                 if  as_child:
                     try:
                         # Try as unsorted tree
         except (MissingNodeOrderBy, PathOverflow, InvalidMoveToDescendant,
             InvalidPosition), e:
             # An error was raised while trying to move the node, then set an
-            # error message and return 400, this will cause a reload on the client
-            # to show the message
-            messages.error(request, u'Exception raised while moving node: %s' % e)
+            # error message and return 400, this will cause a reload on the
+            # client to show the message
+            messages.error(
+                    request, u'Exception raised while moving node: %s' % e)
             return HttpResponseBadRequest(u'Exception raised during move')
-            
+
         return HttpResponse('OK')
-

File treebeard/models.py

View file
         :returns: A queryset of the nodes that must be moved
         to the right. Called only for Node models with :attr:`node_order_by`
 
-        This function was taken from django-mptt (BSD licensed) by Jonathan
-        Buchanan:
-        http://code.google.com/p/django-mptt/source/browse/trunk/mptt/signals.py?spec=svn100&r=100#12
+        This function is based on _insertion_target_filters from django-mptt
+        (BSD licensed) by Jonathan Buchanan:
+        https://github.com/django-mptt/django-mptt/blob/0.3.0/mptt/signals.py
         """
 
         fields, filters = [], []
             engine = settings.DATABASE_ENGINE
         return engine.split('.')[-1]
 
-
     class Meta:
         "Abstract model."
         abstract = True

File treebeard/templatetags/admin_tree.py

View file
 from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
 from django.template import Library
 from django.core.exceptions import ObjectDoesNotExist
-from django.contrib.admin.templatetags.admin_list import result_hidden_fields, result_headers, _boolean_icon
+from django.contrib.admin.templatetags.admin_list import (
+    result_hidden_fields, result_headers, _boolean_icon)
 from django.contrib.admin.util import lookup_field, display_for_field
 from django.utils.safestring import mark_safe
 from django.utils.encoding import smart_unicode, force_unicode
 def items_for_result(cl, result, form):
     """
     Generates the actual list of data.
-    
+
     @jjdelc:
-    This has been shamelessly copied from original django.contrib.admin.templatetags.admin_list.items_for_result in order to alter the dispay for the first element 
+    This has been shamelessly copied from original
+    django.contrib.admin.templatetags.admin_list.items_for_result
+    in order to alter the dispay for the first element
     """
     first = True
     pk = cl.lookup_opts.pk.attname
                     result_repr = escape(getattr(result, f.name))
                 else:
                     result_repr = display_for_field(value, f)
-                if isinstance(f, models.DateField) or isinstance(f, models.TimeField):
+                if (isinstance(f, models.DateField) or
+                        isinstance(f, models.TimeField)):
                     row_class = ' class="nowrap"'
         if force_unicode(result_repr) == '':
             result_repr = mark_safe('&nbsp;')
-        # If list_display_links not defined, add the link tag to the first field
-        if (first and not cl.list_display_links) or field_name in cl.list_display_links:
-            table_tag = {True:'th', False:'td'}[first]
+        # If list_display_links not defined, add the link tag to the
+        # first field
+        if ((first and not cl.list_display_links) or
+                field_name in cl.list_display_links):
+            table_tag = {True: 'th', False: 'td'}[first]
 
             # This spacer indents the nodes based on their depth
-            spacer = '<span class="spacer">&nbsp;</span>' * (result.get_depth() - 1) if first else ''
+            if first:
+                spacer = '<span class="spacer">&nbsp;</span>' * (
+                        result.get_depth() - 1)
+            else:
+                spacer = ''
 
             # This shows a collapse or expand link for nodes with childs
-            collapse = '<a href="#" title="" class="collapse expanded">-</a>' if result.get_children_count() > 0 else '<span class="collapse">&nbsp;</span>'
+            if result.get_children_count():
+                collapse = ('<a href="#" title="" class="collapse expanded">'
+                            '-</a>')
+            else:
+                collapse = '<span class="collapse">&nbsp;</span>'
 
             # Add a <td/> before the first col to show the drag handler
             drag_handler = ''
 
             if first:
-                drag_handler = '<td class="drag-handler"><span>&nbsp;</span></td>'
+                drag_handler = ('<td class="drag-handler">'
+                                '<span>&nbsp;</span></td>')
 
             first = False
             url = cl.url_for_result(result)
                 attr = pk
             value = result.serializable_value(attr)
             result_id = repr(force_unicode(value))[1:]
-            yield mark_safe(u'%s<%s%s>%s %s <a href="%s"%s>%s</a></%s>' % \
-                (drag_handler, table_tag, row_class, spacer, collapse, url, (cl.is_popup and ' onclick="opener.dismissRelatedLookupPopup(window, %s); return false;"' % result_id or ''), conditional_escape(result_repr), table_tag))
+            onclickstr = (
+                ' onclick="opener.dismissRelatedLookupPopup(window, %s);'
+                ' return false;"')
+            yield mark_safe(
+                u'%s<%s%s>%s %s <a href="%s"%s>%s</a></%s>' % (
+                    drag_handler, table_tag, row_class, spacer, collapse, url,
+                    (cl.is_popup and onclickstr % result_id or ''),
+                    conditional_escape(result_repr), table_tag))
         else:
-            # By default the fields come from ModelAdmin.list_editable, but if we pull
-            # the fields out of the form instead of list_editable custom admins
-            # can provide fields on a per request basis
+            # By default the fields come from ModelAdmin.list_editable, but
+            # if we pull the fields out of the form instead of
+            # list_editable custom admins can provide fields on a per
+            # request basis
             if form and field_name in form.fields:
                 bf = form[field_name]
-                result_repr = mark_safe(force_unicode(bf.errors) + force_unicode(bf))
+                result_repr = mark_safe(
+                        force_unicode(bf.errors) + force_unicode(bf))
             else:
                 result_repr = conditional_escape(result_repr)
             yield mark_safe(u'<td%s>%s</td>' % (row_class, result_repr))
     if form and not form[cl.model._meta.pk.name].is_hidden:
-        yield mark_safe(u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
+        yield mark_safe(
+            u'<td>%s</td>' % force_unicode(form[cl.model._meta.pk.name]))
 
 
 def results(cl):
     parent_id = lambda n: n.get_parent().pk if not n.is_root() else 0
     if cl.formset:
         for res, form in zip(cl.result_list, cl.formset.forms):
-            yield res.pk, parent_id(res), res.get_depth(), res.get_children_count(), list(items_for_result(cl, res, form))
+            yield (res.pk, parent_id(res), res.get_depth(),
+                    res.get_children_count(),
+                    list(items_for_result(cl, res, form)))
     else:
         for res in cl.result_list:
-            yield res.pk, parent_id(res), res.get_depth(), res.get_children_count(), list(items_for_result(cl, res, None))
+            yield (res.pk, parent_id(res), res.get_depth(),
+                    res.get_children_count(),
+                    list(items_for_result(cl, res, None)))
 
 
 def check_empty_dict(GET_dict):
     """
-    Returns True if the GET querstring contains on values, but it can contain empty
-    keys.
+    Returns True if the GET querstring contains on values, but it can contain
+    empty keys.
     This is better than doing not bool(request.GET) as an empty key will return
     True
     """
     empty = True
     for k, v in GET_dict.items():
         # Don't disable on p(age) or 'all' GET param
-        if v and k != 'p' and k != 'all': 
+        if v and k != 'p' and k != 'all':
             empty = False
     return empty
 
 
-
 @register.inclusion_tag('admin/tree_change_list_results.html')
 def result_tree(cl, request):
     """
         'results': list(results(cl)),
     }
 
+
 @register.simple_tag
 def treebeard_css():
     """
     css_file = join(path, 'treebeard', 'treebeard-admin.css')
     return LINK_HTML % css_file
 
+
 @register.simple_tag
 def treebeard_js():
     """
 
     # Jquery UI is needed to call disableSelection() on drag and drop so
     # text selections arent marked while dragging a table row
-    # http://www.lokkju.com/blog/archives/143 
+    # http://www.lokkju.com/blog/archives/143
     JQUERY_UI = """
-    <script>(function($){jQuery = $.noConflict(true);})(django.jQuery);</script>
+    <script>
+      (function($){jQuery = $.noConflict(true);})(django.jQuery);
+    </script>
     <script type="text/javascript" src="%s"></script>
     """
     jquery_ui = join(path, 'treebeard', 'jquery-ui-1.8.5.custom.min.js')
 
     scripts = [SCRIPT_HTML % js_file, JQUERY_UI % jquery_ui]
     return ''.join(scripts)
-

File treebeard/templatetags/admin_tree_list.py

View file
     for root_node in cl.model.get_root_nodes():
         tree = tree + '<li>%s</li>' % __subtree(root_node, request)
     return "<ul>%s</ul>" % tree
-
-

File treebeard/tests/models.py

View file
-from django.db import models, transaction
+from django.db import models
 from django.contrib.auth.models import User
 from django.conf import settings
 
     class MP_TestIssue14(MP_Node):
         name = models.CharField(max_length=255)
         users = models.ManyToManyField(User)
-
-