added model inheritance,
authorRadek Czajka <radoslaw.czajka@nowoczesnapolska.org.pl>
Tue, 24 May 2011 14:35:36 +0000 (16:35 +0200)
committerRadek Czajka <radoslaw.czajka@nowoczesnapolska.org.pl>
Tue, 24 May 2011 14:35:36 +0000 (16:35 +0200)
removed auto_add_now,
Book is a Chunk iterator

apps/dvcs/migrations/0001_initial.py
apps/dvcs/models.py
apps/wiki/migrations/0003_auto__add_book__add_chunk__add_unique_chunk_book_number__add_unique_ch.py
apps/wiki/models.py
apps/wiki/templates/wiki/book_detail.html
apps/wiki/templates/wiki/document_list.html
apps/wiki/templates/wiki/tabs/summary_view.html
apps/wiki/views.py

index 0e01d03..16ba34d 100644 (file)
@@ -18,7 +18,7 @@ class Migration(SchemaMigration):
             ('parent', self.gf('django.db.models.fields.related.ForeignKey')(default=None, related_name='children', null=True, blank=True, to=orm['dvcs.Change'])),
             ('merge_parent', self.gf('django.db.models.fields.related.ForeignKey')(default=None, related_name='merge_children', null=True, blank=True, to=orm['dvcs.Change'])),
             ('description', self.gf('django.db.models.fields.TextField')(default='', blank=True)),
-            ('created_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, db_index=True, blank=True)),
+            ('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
         ))
         db.send_create_signal('dvcs', ['Change'])
 
@@ -86,7 +86,7 @@ class Migration(SchemaMigration):
         'dvcs.change': {
             'Meta': {'ordering': "('created_at',)", 'unique_together': "(['tree', 'revision'],)", 'object_name': 'Change'},
             'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
-            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
+            'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
             'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
             'merge_parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'merge_children'", 'null': 'True', 'blank': 'True', 'to': "orm['dvcs.Change']"}),
index 9c9d350..ef11dbe 100644 (file)
@@ -1,3 +1,5 @@
+from datetime import datetime
+
 from django.db import models
 from django.contrib.auth.models import User
 from django.utils.translation import ugettext_lazy as _
@@ -26,7 +28,8 @@ class Change(models.Model):
                         related_name="merge_children")
 
     description = models.TextField(blank=True, default='')
-    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
+    created_at = models.DateTimeField(editable=False, db_index=True, 
+                        default=datetime.now)
 
     class Meta:
         ordering = ('created_at',)
@@ -158,12 +161,12 @@ class Document(models.Model):
         return self.head
 
     def history(self):
-        return self.change_set.filter(revision__gt=0)
+        return self.change_set.filter(revision__gt=-1)
 
     def revision(self):
         rev = self.change_set.aggregate(
                 models.Max('revision'))['revision__max']
-        return rev if rev is not None else 0
+        return rev if rev is not None else -1
 
     def at_revision(self, rev):
         if rev:
@@ -173,12 +176,15 @@ class Document(models.Model):
 
     @staticmethod
     def listener_initial_commit(sender, instance, created, **kwargs):
+        # run for Document and its subclasses
+        if not isinstance(instance, Document):
+            return
         if created:
             instance.head = Change.objects.create(
-                    revision=0,
+                    revision=-1,
                     author=instance.creator,
                     patch=Change.make_patch('', ''),
                     tree=instance)
             instance.save()
 
-models.signals.post_save.connect(Document.listener_initial_commit, sender=Document)
+models.signals.post_save.connect(Document.listener_initial_commit)
index 39154ac..1ce41aa 100644 (file)
@@ -21,12 +21,11 @@ class Migration(SchemaMigration):
 
         # Adding model 'Chunk'
         db.create_table('wiki_chunk', (
-            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
+            ('document_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['dvcs.Document'], unique=True, primary_key=True)),
             ('book', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['wiki.Book'])),
             ('number', self.gf('django.db.models.fields.IntegerField')()),
             ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
             ('comment', self.gf('django.db.models.fields.CharField')(max_length=255)),
-            ('doc', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['dvcs.Document'], unique=True)),
         ))
         db.send_create_signal('wiki', ['Chunk'])
 
@@ -92,7 +91,7 @@ class Migration(SchemaMigration):
         'dvcs.change': {
             'Meta': {'ordering': "('created_at',)", 'unique_together': "(['tree', 'revision'],)", 'object_name': 'Change'},
             'author': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
-            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
+            'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
             'description': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
             'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
             'merge_parent': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'related_name': "'merge_children'", 'null': 'True', 'blank': 'True', 'to': "orm['dvcs.Change']"}),
@@ -117,11 +116,10 @@ class Migration(SchemaMigration):
             'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
         },
         'wiki.chunk': {
-            'Meta': {'ordering': "['number']", 'unique_together': "[['book', 'number'], ['book', 'slug']]", 'object_name': 'Chunk'},
+            'Meta': {'ordering': "['number']", 'unique_together': "[['book', 'number'], ['book', 'slug']]", 'object_name': 'Chunk', '_ormbases': ['dvcs.Document']},
             'book': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['wiki.Book']"}),
             'comment': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
-            'doc': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['dvcs.Document']", 'unique': 'True'}),
-            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
+            'document_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['dvcs.Document']", 'unique': 'True', 'primary_key': 'True'}),
             'number': ('django.db.models.fields.IntegerField', [], {}),
             'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'})
         },
index 66f8a28..f8c9d25 100644 (file)
@@ -6,6 +6,7 @@
 import itertools
 import re
 
+from django.core.urlresolvers import reverse
 from django.db import models
 from django.utils.translation import ugettext_lazy as _
 
@@ -46,9 +47,18 @@ class Book(models.Model):
         """
         instance = cls(*args, **kwargs)
         instance.save()
-        instance.chunk_set.all()[0].doc.commit(author=creator, text=text)
+        instance[0].commit(author=creator, text=text)
         return instance
 
+    def __iter__(self):
+        return iter(self.chunk_set.all())
+
+    def __getitem__(self, chunk):
+        return self.chunk_set.all()[chunk]
+
+    def __len__(self):
+        return self.chunk_set.count()
+
     @staticmethod
     def trim(text, trim_begin=True, trim_end=True):
         """ 
@@ -73,8 +83,8 @@ class Book(models.Model):
         texts = []
         trim_begin = False
         text = ''
-        for chunk in self.chunk_set.all():
-            next_text = chunk.doc.materialize()
+        for chunk in self:
+            next_text = chunk.materialize()
             if not next_text:
                 continue
             if text:
@@ -96,14 +106,13 @@ class Book(models.Model):
 models.signals.post_save.connect(Book.listener_create, sender=Book)
 
 
-class Chunk(models.Model):
+class Chunk(dvcs_models.Document):
     """ An editable chunk of text. Every Book text is divided into chunks. """
 
     book = models.ForeignKey(Book)
     number = models.IntegerField()
     slug = models.SlugField()
     comment = models.CharField(max_length=255)
-    doc = models.ForeignKey(dvcs_models.Document, editable=False, unique=True, null=True)
 
     class Meta:
         unique_together = [['book', 'number'], ['book', 'slug']]
@@ -112,10 +121,8 @@ class Chunk(models.Model):
     def __unicode__(self):
         return "%d-%d: %s" % (self.book_id, self.number, self.comment)
 
-    def save(self, *args, **kwargs):
-        if self.doc is None:
-            self.doc = dvcs_models.Document.objects.create()
-        super(Chunk, self).save(*args, **kwargs)
+    def get_absolute_url(self):
+        return reverse("wiki_editor", args=[self.book.slug, self.slug])
 
     @classmethod
     def get(cls, slug, chunk=None):
@@ -126,7 +133,7 @@ class Chunk(models.Model):
 
     def pretty_name(self):
         return "%s, %s (%d/%d)" % (self.book.title, self.comment, 
-                self.number, self.book.chunk_set.count())
+                self.number, len(self.book))
 
 
 
index f30ed36..0a03d8b 100755 (executable)
@@ -6,8 +6,8 @@
     <h1>{{ book.title }}</h1>
 
 <p>
-    {% for chunk in book.chunk_set.all %}
-        <a target="_blank" href="{% url wiki_editor book.slug chunk.slug %}">{{ chunk.comment }}</a><br/>
+    {% for chunk in book %}
+        <a target="_blank" href="{{ chunk.get_absolute_url }}">{{ chunk.comment }}</a><br/>
     {% endfor %}
 </p>
 
index bec1556..fd4760e 100644 (file)
@@ -41,9 +41,9 @@ $(function() {
                                 href="{% url wiki_editor book.slug %}">
                                 [{% trans "edit" %}]</a>
                     {% else %}
-                        {% for chunk in book.chunk_set.all %}
+                        {% for chunk in book %}
                             <a target="_blank" data-id="{{ book.slug }}"
-                                href="{% url wiki_editor book.slug chunk.slug %}">
+                                href="{{ chunk.get_absolute_url }}">
                                 [<span class='chunkno'>{{ forloop.counter }}.</span>
                                 {{ chunk.comment }}</a>]<br/>
                         {% endfor %}
index 283698b..73eece2 100644 (file)
                </p>
                <p>
                        <label>{% trans "Current version" %}:</label>
-                       {{ chunk.doc.revision }} ({{ chunk.doc.head.created_at }})
+                       {{ chunk.revision }} ({{ chunk.head.created_at }})
                <p>
                        <label>{% trans "Last edited by" %}:</label>
-                       {{ chunk.doc.head.author }}
+                       {{ chunk.head.author }}
                </p>
                <p>
                        <label for="gallery">{% trans "Link to gallery" %}:</label>
index 378701c..b303542 100644 (file)
@@ -206,7 +206,7 @@ def upload(request):
 @decorator_from_middleware(GZipMiddleware)
 def text(request, slug, chunk=None):
     try:
-        doc = Chunk.get(slug, chunk).doc
+        doc = Chunk.get(slug, chunk)
     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
         raise Http404
 
@@ -290,7 +290,7 @@ def revert(request, slug, chunk=None):
     form = DocumentTextRevertForm(request.POST, prefix="textrevert")
     if form.is_valid():
         try:
-            doc = Chunk.get(slug, chunk).doc
+            doc = Chunk.get(slug, chunk)
         except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
             raise Http404
 
@@ -356,7 +356,7 @@ def diff(request, slug, chunk=None):
         revB = None
 
     try:
-        doc = Chunk.get(slug, chunk).doc
+        doc = Chunk.get(slug, chunk)
     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
         raise Http404
     docA = doc.at_revision(revA).materialize()
@@ -369,7 +369,7 @@ def diff(request, slug, chunk=None):
 @never_cache
 def revision(request, slug, chunk=None):
     try:
-        doc = Chunk.get(slug, chunk).doc
+        doc = Chunk.get(slug, chunk)
     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
         raise Http404
     return http.HttpResponse(str(doc.revision()))
@@ -379,7 +379,7 @@ def revision(request, slug, chunk=None):
 def history(request, slug, chunk=None):
     # TODO: pagination
     try:
-        doc = Chunk.get(slug, chunk).doc
+        doc = Chunk.get(slug, chunk)
     except (Chunk.MultipleObjectsReturned, Chunk.DoesNotExist):
         raise Http404