Commits

Gustavo Picon  committed 18448a6

Removed tbexample

  • Participants
  • Parent commits c7e67db

Comments (0)

Files changed (16)

File tbexample/__init__.py

Empty file removed.

File tbexample/admin.py

-import datetime
-
-from django.contrib import admin
-from treebeard.admin import TreeAdmin
-
-from tbexample.models import MP_Post, AL_Post, NS_Post
-
-
-class TreeExampleAdmin(TreeAdmin):
-    def save_form(self, request, form, change):
-        if not change:
-            form.cleaned_data['created'] = datetime.datetime.now()
-        return form.save(commit=False)
-
-
-class MP_Admin(TreeExampleAdmin):
-    pass
-
-
-class AL_Admin(TreeExampleAdmin):
-    pass
-
-
-class NS_Admin(TreeExampleAdmin):
-    pass
-
-
-admin.site.register(MP_Post, MP_Admin)
-admin.site.register(AL_Post, AL_Admin)
-admin.site.register(NS_Post, NS_Admin)

File tbexample/forms.py

-from django import forms
-from django.db import transaction
-
-
-class CommentForm(forms.Form):
-    """ A fancy comment form.
-    """
-    author = forms.CharField(label='Author',
-                             max_length=255)
-    comment = forms.CharField(label='Comment',
-                              widget=forms.Textarea)
-    parent = forms.IntegerField(label='Parent',
-                                required=False,
-                                widget=forms.HiddenInput)
-
-
-    @transaction.commit_on_success
-    def clean_parent(self):
-        """ Parent field validation
-        """
-        if self.root is None:
-            self.add_method = self.tbmodel.add_root
-            return
-        parent_id = self.cleaned_data['parent']
-        if not parent_id:
-            parent_id = self.root.id
-        try:
-            parent_obj = self.tbmodel.objects.get(id=parent_id)
-        except self.tbmodel.DoesNotExist:
-            raise forms.ValidationError('Invalid comment id: %d' %
-                                        (parent_id,))
-        if parent_obj != self.root and not parent_obj.is_descendant_of(self.root):
-            raise forms.ValidationError(
-                'Comment %d does not belong to convo %d (wrong page)' %
-                (parent_id, self.root.id,))
-        self.add_method = parent_obj.add_child
-
-

File tbexample/models.py

-# -*- coding: utf-8 -*-
-"""
-
-    tbexample.models
-    ----------------
-
-    django-treebeard - models for the example app
-
-    :copyright: 2008-2010 by Gustavo Picon
-    :license: Apache License 2.0
-
-"""
-
-from django.db import models
-
-from treebeard.mp_tree import MP_Node
-from treebeard.al_tree import AL_Node
-from treebeard.ns_tree import NS_Node
-
-
-class MP_Post(MP_Node):
-    author  = models.CharField(max_length=255)
-    comment = models.TextField()
-    #created = models.DateTimeField(auto_now_add=True)
-    # Exception Value: Cannot use None as a query value
-    created = models.DateTimeField(editable=False)
-
-    node_order_by = ['created']
-
-    @models.permalink
-    def get_absolute_url(self):
-        return ('node-view', ('mp', str(self.id),))
-
-    def __unicode__(self):
-        return u'MP_Post %d: %s' % (self.id, self.comment)
-
-    class Meta:
-        verbose_name = 'Materialized Path Tree Post'
-
-        # when adding a custom Meta class to a MP model, the ordering must be
-        # set again
-        ordering = ['path']
-
-MP_Post._meta.get_field('path').max_length = 255
-
-
-class AL_Post(AL_Node):
-    author  = models.CharField(max_length=255)
-    comment = models.TextField()
-    #created = models.DateTimeField(auto_now_add=True)
-    # Exception Value: Cannot use None as a query value
-    created = models.DateTimeField(editable=False)
-
-    parent = models.ForeignKey('self',
-                               related_name='children_set',
-                               null=True,
-                               db_index=True)
-    node_order_by = ['created']
-
-    @models.permalink
-    def get_absolute_url(self):
-        return ('node-view', ('al', str(self.id),))
-
-    def __unicode__(self):
-        return u'AL_Post %d: %s' % (self.id, self.comment)
-
-    class Meta:
-        verbose_name = 'Adjacenty List Tree Post'
-
-
-class NS_Post(NS_Node):
-    author  = models.CharField(max_length=255)
-    comment = models.TextField()
-    #created = models.DateTimeField(auto_now_add=True)
-    # Exception Value: Cannot use None as a query value
-    created = models.DateTimeField(editable=False)
-
-    node_order_by = ['created']
-
-    @models.permalink
-    def get_absolute_url(self):
-        return ('node-view', ('ns', str(self.id),))
-
-    def __unicode__(self):
-        return u'NS_Post %d: %s' % (self.id, self.comment)
-
-    class Meta:
-        verbose_name = 'Nested Set Tree Post'
-
-        # when adding a custom Meta class to a NS model, the ordering must be
-        # set again
-        ordering = ['tree_id', 'lft']

File tbexample/templates/tbexample/base.html

-<html>
-  <head>
-    <title>Threaded forum example, built with django-treebeard</title>
-
-    {% block javascript %}
-    {% endblock %}
-
-    <style type="text/css">
-      div.comment {
-          border-style: solid;
-          border-width: 1px;
-          margin-top: 5px;
-          margin-bottom: 5px;
-          padding: 10px;
-      }
-      form#reply-form {
-          border-style: solid;
-          border-width: 1px;
-          padding: 10px;
-      }
-    </style>
-  </head>
-  <body>
-    <h1>
-    <a href="{% url main-view treetype %}">{{ treetype|upper }} Tree forum example</a>,
-    built with <a href="https://tabo.pe/projects/django-treebeard/">django-treebeard</a>
-    </h1>
-    
-    <p>
-    (<a
-    href="http://code.tabo.pe/django-treebeard/src/tip/tbexample/">source</a>)
-    </p>
-
-
-    {% block body %}
-    {% endblock %}
-
-    <hr/>
-    SQL queries used to build this page:
-    <br/>
-    <ol>
-    {% for query in sql_queries %}
-      <li>({{ query.time }}s) {{ query.sql }}</li>
-    {% endfor %}
-    </ol>
-  </body>
-</html>
-

File tbexample/templates/tbexample/choose.html

-<html>
-  <head>
-    <title>Threaded forum example, built with django-treebeard</title>
-  </head>
-
-  <body>
-    
-    <h1>
-    Forum example,
-    built with <a href="https://tabo.pe/projects/django-treebeard/">django-treebeard</a>
-    </h1>
-
-    <p>
-    (<a
-    href="http://code.tabo.pe/django-treebeard/src/tip/tbexample/">source</a>)
-    </p>
-
-    Choose a tree model:
-
-    <ul>
-      <li><a href="{% url main-view "al" %}">Adjacency List Tree (AL)</a></li>
-      <li><a href="{% url main-view "mp" %}">Materialized Path Tree (MP)</a></li>
-      <li><a href="{% url main-view "ns" %}">Nested Sets Tree (NS)</a></li>
-    </ul>
-  </body>
-</html>

File tbexample/templates/tbexample/comment.html

-      <div style="margin-left: {{ node.get_depth }}em;" class="comment"
-           id="comment_{{ node.id }}">
-        <div>
-          {{ node.author }}, on {{ node.created }}, said:
-        </div>
-        <div>
-          {{ node.comment|linebreaks }}
-        </div>
-        <div>
-          {% ifequal node.get_depth 1 %}
-            <a href="{{ node.get_absolute_url }}">#</a>
-            ({{ count }}
-            comment{{ count|pluralize }} in this conversation)
-          {% else %}
-            <a href="#comment_{{ node.id }}">#</a>
-            ({{ count }}
-            repl{{ count|pluralize:"y,ies" }})
-          {% endifequal %}
-          {% if not mainpage %}
-            <a href="#reply-form" class="reply-link"
-               id="reply-{{ node.id }}">reply!</a>
-          {% endif %}
-          (<a href="{{ node.get_absolute_url }}delete/">delete</a>)
-        </div>
-      </div>
-

File tbexample/templates/tbexample/convo.html

-{% extends "tbexample/base.html" %}
-
-{% block javascript %}
-    <script type="text/javascript"
-      src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
-    </script>
-    <script type="text/javascript">
-        $(function() {
-            $(".reply-link").click(function(event) {
-                $("#id_parent").attr("value", $(this).attr("id").substring(6));
-            });
-        })
-    </script>
-{% endblock %}
-
-{% block body %}
-    <h2>Conversation list</h2>
-
-    {% for node, count in nodes %}
-        {% include "tbexample/comment.html" %}
-    {% endfor %}
-
-    {% include "tbexample/form.html" %}
-
-{% endblock %}

File tbexample/templates/tbexample/delete.html

-{% extends "tbexample/base.html" %}
-
-{% block body %}
-    Removed comment(s) and descendants.
-
-    Please note that the 'SELECT LIMIT 100'/'DELETE' combos you see here are
-    Django's way of removing objects from the DB.
-{% endblock %}
-

File tbexample/templates/tbexample/form.html

-
-    <form action="./reply/" method="POST" id="reply-form">
-      {{ form.as_p }}
-
-      <input type="submit" value="Send">
-      <input type="reset">
-    </form>

File tbexample/templates/tbexample/loaddata.html

-{% extends "tbexample/base.html" %}
-
-{% block body %}
-    Loaded random data.
-{% endblock %}

File tbexample/templates/tbexample/loadflood.html

-{% extends "tbexample/base.html" %}
-
-{% block body %}
-    Please wait a few minutes before loading random posts again.
-{% endblock %}
-

File tbexample/templates/tbexample/main.html

-{% extends "tbexample/base.html" %}
-
-{% block body %}
-    (<a href="{% url load-data treetype %}">load random data</a>)
-    (<a href="{% url delete-all treetype %}">remove all nodes</a>)
-
-    Add a new discussion:
-
-    {% include "tbexample/form.html" %}
-
-    <h2>Conversation list</h2>
-    <p>
-      There are currently
-      {{ nodes|length }} discussion{{ nodes|length|pluralize }}
-      ({{ total_comments }} total comment{{ total_comments|pluralize }}):
-    </p>
-
-    {% for node, count in nodes %}
-        {% include "tbexample/comment.html" %}
-    {% endfor %}
-{% endblock %}

File tbexample/templates/tbexample/posted.html

-{% extends "tbexample/base.html" %}
-
-
-
-{% block body %}
-    You added a new comment. Click <a href="{{ link }}">here</a> to see it.
-{% endblock %}

File tbexample/urls.py

-import os
-from django.contrib import admin
-from django.conf.urls.defaults import *
-import treebeard
-from tbexample.views import convo, load_random_data, delete_node, delete_all
-from tbexample.views import choose
-
-admin.autodiscover()
-
-baseurl = r'^(?P<treetype>mp|al|ns)/'
-lurls = [
-    (r'loaddata/$', load_random_data, 'load-data'),
-    (r'delete_all/$', delete_all, 'delete-all'),
-    (r'(?P<node_id>\d+)/delete/$', delete_node, 'delete-node'),
-    (r'(?P<node_id>\d+)/reply/$', convo, 'reply-view'),
-    (r'(?P<node_id>\d+)/$', convo, 'node-view'),
-    (r'$', convo, 'main-view')
-]
-
-path = os.path.dirname(treebeard.__file__)
-static_path = os.path.normpath(os.path.join(path, 'static/'))
-
-urlpatterns = patterns('',
-    (r'^admin/', include(admin.site.urls)),
-    (r'^static/(?P<path>.*)$', 'django.views.static.serve',
-        {'document_root': static_path, 'show_indexes': True}))
-
-for pat, view, name in lurls:
-    urlpatterns += patterns('', url('%s%s' % (baseurl, pat), view, name=name))
-urlpatterns += patterns('', url('^$', choose, name='choose-tree'))

File tbexample/views.py

-
-import datetime
-import random
-
-from django import forms
-from django.db import transaction
-from django.http import HttpResponseRedirect
-from django.db import connection
-from django.shortcuts import render_to_response, get_object_or_404
-from django.core.cache import cache
-
-from tbexample.models import MP_Post, AL_Post, NS_Post
-from tbexample.forms import CommentForm
-
-
-def treetype2model(treetype):
-    """ Returns the tree model for a given tree type from the url
-    """
-    return {'mp': MP_Post,
-            'al': AL_Post,
-            'ns': NS_Post}[treetype]
-
-
-@transaction.commit_on_success
-def load_random_data(request, treetype):
-    """ Makes lots of dummy posts.
-    """
-    tbmodel = treetype2model(treetype)
-    data = {'sql_queries': connection.queries,
-            'treetype': treetype}
-
-    key = 'treebeard_tbexample_loadfloodprot_%s' % treetype
-    if cache.get(key):
-        return render_to_response('tbexample/loadflood.html', data)
-    cache.set(key, True, 60*5)
-
-    interval = range(1,6)
-    vals = {1: 4, 2: 10, 3: 25, 4: 50, 5: 50}
-    for depth in interval:
-        num = vals[depth]
-        if depth > 1:
-            if treetype == 'al':
-                nodes = [obj for obj in tbmodel.objects.all()
-                         if obj.get_depth() == depth-1]
-            else:
-                nodes = list(tbmodel.objects.filter(depth=depth-1))
-        for i in range(num):
-            if depth == 1:
-                meth = tbmodel.add_root
-            else:
-                node = nodes[random.randint(0, len(nodes)-1)]
-                if treetype == 'ns':
-                    node = tbmodel.objects.get(pk=node.id)
-                meth = node.add_child
-            obj = meth(author='author_%d' % (i,),
-                 comment='lorem ipsum! %d' % (random.randint(1000000000,
-                                                             9999999999), ),
-                 created=datetime.datetime.now())
-    return render_to_response('tbexample/loaddata.html', data)
-
-
-@transaction.commit_on_success
-def delete_node(request, treetype, node_id):
-    """ View to remove a message and it's replies
-    """
-    tbmodel = treetype2model(treetype)
-    data = {'sql_queries': connection.queries,
-            'treetype': treetype}
-    node = get_object_or_404(tbmodel, id=node_id)
-    node.delete()
-    return render_to_response('tbexample/delete.html', data)
-
-
-@transaction.commit_on_success
-def delete_all(request, treetype):
-    """ Remove all messages
-    """
-    tbmodel = treetype2model(treetype)
-    data = {'sql_queries': connection.queries,
-            'treetype': treetype}
-    tbmodel.objects.all().delete()
-    return render_to_response('tbexample/delete.html', data)
-
-
-@transaction.commit_on_success
-def convo(request, treetype, node_id=None):
-    """ convo view~
-    """
-    tbmodel = treetype2model(treetype)
-    data = {'sql_queries': connection.queries,
-            'treetype': treetype}
-    if node_id:
-        root = get_object_or_404(tbmodel, id=node_id)
-        if root.get_depth() != 1:
-            # meh not really a root node, redirecting...
-            return HttpResponseRedirect('%s#comment_%d' %
-                (root.get_root().get_absolute_url(), root.id))
-    else:
-        root = None
-
-    if request.method == 'POST':
-        form = CommentForm(request.POST)
-        form.root = root
-        form.tbmodel = tbmodel
-        if form.is_valid():
-            obj = form.add_method(
-                author=form.cleaned_data['author'],
-                comment=form.cleaned_data['comment'],
-                created=datetime.datetime.now())
-            if not root:
-                root = obj
-            data['link'] = '%s#comment_%d' % \
-                           (root.get_absolute_url(), obj.id)
-            return render_to_response('tbexample/posted.html', data)
-    else:
-        form = CommentForm()
-        form.root = root
-        form.tbmodel = tbmodel
-
-    data['form'] = form
-    if node_id:
-        template_html = 'tbexample/convo.html'
-        descendants = root.get_descendants()
-        nodes = [(root, len(descendants))] + [
-            (node, node.get_children_count())
-            for node in descendants
-        ]
-        data['mainpage'] = False
-        data['nodes'] = nodes
-        form.fields['parent'].widget = forms.TextInput()
-    else:
-        template_html = 'tbexample/main.html'
-        data['mainpage'] = True
-        data['nodes'] = [(node, node.descendants_count)
-                         for node in tbmodel.get_descendants_group_count()]
-        data['total_comments'] = len(data['nodes']) + \
-                                 sum([count for _, count in data['nodes']])
-        data['treetype'] = treetype
-    return render_to_response(template_html, data)
-
-
-def choose(request):
-    return render_to_response('tbexample/choose.html', {})
-
-