Keegan Carruthers-Smith avatar Keegan Carruthers-Smith committed dbfb3cc

initial commit.

Comments (0)

Files changed (23)

+syntax: glob
+*.pyc
+example_project/test.db
+========================
+ Django File Flat Pages
+========================
+
+This is a Django App which makes FlatPage fixtures nicer to edit. More
+explanation to come.
Add a comment to this file

example_project/__init__.py

Empty file added.

Add a comment to this file

example_project/app/__init__.py

Empty file added.

example_project/app/flatpages/about.rst

+.. url = /about/
+.. title = About
+.. template_name = flatpages/rst.html
+
+=======
+ About
+=======
+
+This is an about page rendered from ReST_.
+
+A Sub-Heading
+=============
+
+1. Item 1
+2. Item 2
+
+.. _ReST: http://docutils.sourceforge.net/

example_project/app/flatpages/index.rst

+.. url = /
+.. title = django-fileflatpages
+.. template_name = flatpages/rst.html
+
+=======
+ Index
+=======
+
+This is a example_project showing of django-fileflatpages. This file is a
+FlatPage that was rendered from ReST_. The rst file is at
+example_project/app/flatpages/index.rst and was inserted into the database
+with the command **loadflatpages**.
+
+Visit the About_ page for another ReST file, or visit Test_ for a page
+rendered from HTML.
+
+.. _ReST: http://docutils.sourceforge.net/
+.. _About: /about/
+.. _Test: /test/

example_project/app/flatpages/test.html

+<!-- url = /test/ -->
+<!-- title = Test Page -->
+
+<h2>Test Page</h2>
+
+This test page is made from raw <b>HTML</b>.

example_project/app/models.py

+from django.db import models
+
+# Create your models here.

example_project/app/templates/flatpages/default.html

+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+    "http://www.w3.org/TR/REC-html40/loose.dtd">
+<html>
+<head>
+<title>{{ flatpage.title }}</title>
+</head>
+<body>
+{{ flatpage.content }}
+</body>
+</html>

example_project/app/templates/flatpages/rst.html

+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
+    "http://www.w3.org/TR/REC-html40/loose.dtd">
+<html>
+<head>
+<title>{{ flatpage.title }}</title>
+</head>
+<body>
+{% load markup %}
+{{ flatpage.content|restructuredtext }}
+</body>
+</html>

example_project/app/tests.py

+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.assertEqual(1 + 1, 2)

example_project/app/views.py

+# Create your views here.

example_project/manage.py

+#!/usr/bin/env python
+from django.core.management import execute_manager
+import imp
+try:
+    imp.find_module('settings') # Assumed to be in the same directory.
+except ImportError:
+    import sys
+    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
+    sys.exit(1)
+
+import settings
+
+if __name__ == "__main__":
+    execute_manager(settings)

example_project/requirements.txt

+Django==1.3
+docutils==0.8

example_project/settings.py

+import os.path
+__dir__ = os.path.dirname(os.path.abspath(__file__))
+
+DEBUG = True
+TEMPLATE_DEBUG = DEBUG
+SITE_ID = 1
+
+DATABASES = {
+    'default': {
+        'ENGINE': 'django.db.backends.sqlite3',
+        'NAME': os.path.join(__dir__, 'test.db'),
+        'USER': '',
+        'PASSWORD': '',
+        'HOST': '',
+        'PORT': '',
+    }
+}
+
+TEMPLATE_LOADERS = (
+    'django.template.loaders.filesystem.Loader',
+    'django.template.loaders.app_directories.Loader',
+)
+
+MIDDLEWARE_CLASSES = (
+    'django.middleware.common.CommonMiddleware',
+    'django.contrib.sessions.middleware.SessionMiddleware',
+    'django.middleware.csrf.CsrfViewMiddleware',
+    'django.contrib.auth.middleware.AuthenticationMiddleware',
+    'django.contrib.messages.middleware.MessageMiddleware',
+    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
+)
+
+ROOT_URLCONF = 'example_project.urls'
+
+INSTALLED_APPS = (
+    'django.contrib.auth',
+    'django.contrib.contenttypes',
+    'django.contrib.sessions',
+    'django.contrib.sites',
+    'django.contrib.messages',
+    'django.contrib.flatpages',
+    'django.contrib.admin',
+    'django.contrib.markup',
+    'fileflatpages',
+    'example_project.app',
+)

example_project/urls.py

+from django.conf.urls.defaults import patterns, include, url
+
+from django.contrib import admin
+admin.autodiscover()
+
+urlpatterns = patterns(
+    '',
+    url(r'^admin/', include(admin.site.urls)),
+)
Add a comment to this file

fileflatpages/__init__.py

Empty file added.

Add a comment to this file

fileflatpages/management/__init__.py

Empty file added.

Add a comment to this file

fileflatpages/management/commands/__init__.py

Empty file added.

fileflatpages/management/commands/loadflatpages.py

+import os.path
+import re
+
+from django.conf import settings
+from django.core.management.base import BaseCommand
+from django.db import connections, router, transaction, DEFAULT_DB_ALIAS
+from django.db.models import get_apps
+
+from fileflatpages.models import FileFlatPage
+
+
+class Command(BaseCommand):
+    help = 'Installs the flatpage fixtures in the database.'
+    option_list = BaseCommand.option_list
+
+    comment_re = re.compile(r'^(#|\.\.|<!---?|//)(.*?)(-?-->)?$')
+    required_fields = ('url', 'title')
+    other_fields = ('enable_comments', 'template_name', 'registration_required')
+
+    def __init__(self, *args, **kwargs):
+        super(Command, self).__init__(*args, **kwargs)
+        fields = '|'.join(self.required_fields + self.other_fields)
+        self.keyvalue_re = re.compile(r'^\s*(%s)\s*(?:=|:)(.*)$' % fields)
+
+    def add_fixture(self, app_name, flatpages_path, path):
+        file_path = os.path.join(flatpages_path, path)
+        fin = file(file_path)
+        lines = fin.readlines()
+        fin.close()
+
+        # Get the fields from the comments at the top of the file
+        fields = {}
+        for line in lines:
+            match = self.comment_re.match(line)
+            if match is None:
+                break
+            match = self.keyvalue_re.match(match.group(2))
+            if match is None:
+                continue
+
+            key, value = match.groups()
+            if key in fields:
+                self.stdout.write("WARNING: Key '%s' is repeated in file %s\n"
+                                  % (key, file_path))
+            fields[key] = value.strip()
+
+        # Check we have all the required fields
+        for field in self.required_fields:
+            if field not in fields:
+                self.stdout.write("WARNING: Key '%s' is required but missing in %s\n"
+                                  % (field, file_path))
+                return False
+
+        # Set the fields on the model instance and save
+        flatpage, _ = FileFlatPage.objects.get_or_create(app=app_name, path=path)
+        for field, value in fields.iteritems():
+            setattr(flatpage, field, value)
+        flatpage.content = ''.join(lines)
+        flatpage.sites = [settings.SITE_ID]
+        flatpage.save()
+
+        return True
+
+    def handle(self, *fixture_labels, **options):
+        # Do this in a transaction
+        using = options.get('database', DEFAULT_DB_ALIAS)
+        transaction.commit_unless_managed(using=using)
+        transaction.enter_transaction_management(using=using)
+        transaction.managed(True, using=using)
+
+        for app_name, app_path in self.app_modules():
+            flatpages_path = os.path.join(os.path.dirname(app_path), 'flatpages')
+
+            if not os.path.exists(flatpages_path):
+                continue
+            if not os.path.isdir(flatpages_path):
+                self.stdout.write('WARNING: %s is not a directory\n'
+                                  % flatpages_path)
+                continue
+
+            self.stdout.write('Processing flatpage fixtures in %s\n'
+                              % flatpages_path)
+            for path in os.listdir(flatpages_path):
+                if self.add_fixture(app_name, flatpages_path, path):
+                    self.stdout.write('Added flatpage fixture %s from %s\n'
+                                      % (path, app_name))
+
+        # Commit our transaction
+        transaction.commit(using=using)
+        transaction.leave_transaction_management(using=using)
+
+    @classmethod
+    def app_modules(cls):
+        for app in get_apps():
+            name, _ = app.__name__.rsplit('.', 1)
+            if hasattr(app, '__path__'):
+                # It's a 'models/' subpackage
+                for path in app.__path__:
+                    yield (name, path)
+            else:
+                # It's a models.py module
+                yield (name, app.__file__)

fileflatpages/models.py

+from django.contrib.flatpages.models import FlatPage
+from django.db import models
+
+class FileFlatPage(FlatPage):
+    app = models.TextField()
+    path = models.TextField()

fileflatpages/tests.py

+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.assertEqual(1 + 1, 2)

fileflatpages/views.py

+# Create your views here.
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.