Exemplo n.º 1
0
    def configure(self, site, engine):

        """
        configure the django environment
        """
        self.site = site
        self.engine = engine
        self.preprocessor = engine.preprocessor if hasattr(engine, "preprocessor") else None

        try:
            from django.conf import global_settings

            defaults = global_settings.__dict__
            if site.config:
                defaults.update(site.config)

            if site.config:
                template_dirs = (unicode(site.config.content_root_path), unicode(site.config.layout_root_path))
            else:
                template_dirs = (unicode(self.sitepath),)
            defaults.update({"TEMPLATE_DIRS": template_dirs})
            settings.configure(**defaults)
            add_to_builtins("hyde.ext.templates.django_template.templatetags.hydetags")
        except Exception, err:
            logger.error("Site settings are not defined properly")
            logger.error(err)
            raise ValueError(
                "The given site_path [%s] has invalid settings. "
                "Give a valid path or run create to create a new site." % self.sitepath
            )
Exemplo n.º 2
0
    def setup(self):
        """
        Configure django to use both our template and pages folder as locations
        to look for included templates.
        """

        settings = {
            "TEMPLATE_DIRS": [self.template_path, self.page_path],
            "INSTALLED_APPS": ['django_markwhat'],
        }

        if self.locale is not None:
            settings.update({
                "USE_I18N": True,
                "USE_L10N": False,
                "LANGUAGE_CODE":  self.locale,
                "LOCALE_PATHS": [self.locale_path],
            })

        django.conf.settings.configure(**settings)

        # - Importing here instead of the top-level makes it work on Python 3.x (!)
        # - loading add_to_builtins from loader implictly loads the loader_tags built-in
        # - Injecting our tags using add_to_builtins ensures that Cactus tags don't require an import
        from django.template.loader import add_to_builtins
        add_to_builtins('cactus.template_tags')
Exemplo n.º 3
0
    def setup(self):
        """
        Configure django to use both our template and pages folder as locations
        to look for included templates.
        """

        settings = {
            "TEMPLATE_DIRS": [self.template_path, self.page_path],
            "INSTALLED_APPS": ['django_markwhat'],
        }

        if self.locale is not None:
            settings.update({
                "USE_I18N": True,
                "USE_L10N": False,
                "LANGUAGE_CODE": self.locale,
                "LOCALE_PATHS": [self.locale_path],
            })

        django.conf.settings.configure(**settings)

        # - Importing here instead of the top-level makes it work on Python 3.x (!)
        # - loading add_to_builtins from loader implictly loads the loader_tags built-in
        # - Injecting our tags using add_to_builtins ensures that Cactus tags don't require an import
        from django.template.loader import add_to_builtins
        add_to_builtins('cactus.template_tags')
Exemplo n.º 4
0
def register_all(site):
    global SITE
    SITE = site
    basedir = os.path.dirname(__file__)
    for libname in os.listdir(basedir):
        match = re_validfile.search(libname)
        if match:
            add_to_builtins('cactus.templatetags.{0}'.format(match.group('name')))
Exemplo n.º 5
0
    def _dorender(self, templatename, context):
        from django.template import loader

        mydir = os.path.dirname(os.path.abspath(__file__))
        templatedir = os.path.abspath(os.path.join(mydir, '..','templates','gnmoptin'))

        loader.add_to_builtins('portal.plugins.gnmoptin.tests.loader_tags')

        return loader.render_to_string(os.path.join(templatedir, templatename),context)
	def initialize():

		#setting up TEMPLATE_DIRS to support themes	
		if not ExpedientThemeManager._theme == ExpedientThemeManager._default:
			ThemeTemplateDirs = ExpedientThemeManager.setThemeTemplateDirs()
			settings.TEMPLATE_DIRS = ThemeTemplateDirs + settings.TEMPLATE_DIRS
		
		#loading url templatetag
		from django.template.loader import add_to_builtins
		add_to_builtins('expedient.common.utils.templatetags.url')
Exemplo n.º 7
0
    def initialize():

        #setting up TEMPLATE_DIRS to support themes
        if not ExpedientThemeManager._theme == ExpedientThemeManager._default:
            ThemeTemplateDirs = ExpedientThemeManager.setThemeTemplateDirs()
            settings.TEMPLATE_DIRS = ThemeTemplateDirs + settings.TEMPLATE_DIRS

        #loading url templatetag
        from django.template.loader import add_to_builtins
        add_to_builtins('expedient.common.utils.templatetags.url')
Exemplo n.º 8
0
        def initialize():

                #setting up TEMPLATE_DIRS to support themes     
                if not OptinThemeManager._theme == OptinThemeManager._default:
                        ThemeTemplateDirs = OptinThemeManager.setThemeTemplateDirs()
                        settings.TEMPLATE_DIRS = tuple(ThemeTemplateDirs) + settings.TEMPLATE_DIRS

                #loading url templatetag
                from django.template.loader import add_to_builtins
                add_to_builtins('openflow.common.utils.templatetags.url')
Exemplo n.º 9
0
    def initialize():

        #setting up TEMPLATE_DIRS to support themes
        if not OptinThemeManager._theme == OptinThemeManager._default:
            ThemeTemplateDirs = OptinThemeManager.setThemeTemplateDirs()
            settings.TEMPLATE_DIRS = tuple(
                ThemeTemplateDirs) + settings.TEMPLATE_DIRS

        #loading url templatetag
        from django.template.loader import add_to_builtins
        add_to_builtins('openflow.common.utils.templatetags.url')
Exemplo n.º 10
0
	def initialize():
		
		#setTemplateDirs

		theme_templates = ThemeManager.getThemeTemplatePath(ThemeManager._templateDir)
		
		
		if not (theme_templates[0] == settings.TEMPLATE_DIRS[0]):
			settings.TEMPLATE_DIRS = (theme_templates,) + settings.TEMPLATE_DIRS #theme_templates need tuple conversion

		#Load the custom URL templatetag
		from django.template.loader import add_to_builtins
		add_to_builtins('vt_manager_kvm.views.templatetags.url')
Exemplo n.º 11
0
def main():
    try:
        filename = sys.argv[1]
    except IndexError:
        sys.exit('Please provide template file path as argument, usage:\n\n\t$ firedj index.html\n')

    curdir = os.path.dirname(os.path.abspath(filename))

    settings.configure()
    settings.TEMPLATE_DIRS = [curdir]

    add_to_builtins('django.template.loader_tags')

    print render(filename)
Exemplo n.º 12
0
    def initialize():

        #setTemplateDirs

        theme_templates = ThemeManager.getThemeTemplatePath(
            ThemeManager._templateDir)

        if not (theme_templates[0] == settings.TEMPLATE_DIRS[0]):
            settings.TEMPLATE_DIRS = (
                theme_templates,
            ) + settings.TEMPLATE_DIRS  #theme_templates need tuple conversion

        #Load the custom URL templatetag
        from django.template.loader import add_to_builtins
        add_to_builtins('vt_manager.views.templatetags.url')
Exemplo n.º 13
0
def main():
    try:
        filename = sys.argv[1]
    except IndexError:
        sys.exit(
            'Please provide template file path as argument, usage:\n\n\t$ firedj index.html\n'
        )

    curdir = os.path.dirname(os.path.abspath(filename))

    settings.configure()
    settings.TEMPLATE_DIRS = [curdir]

    add_to_builtins('django.template.loader_tags')

    print render(filename)
Exemplo n.º 14
0
def setup_pygments():
    
    from django.conf import settings

    vendor_path = os.path.join(os.path.dirname(__file__), "..", "vendor")

    if not vendor_path in sys.path:
        sys.path.append(vendor_path)

    print vendor_path

    if not "django_pygments" in settings.INSTALLED_APPS:
        settings.INSTALLED_APPS.append("django_pygments")

    from django.template.loader import add_to_builtins

    add_to_builtins('django_pygments.templatetags.pygmentify')
Exemplo n.º 15
0
	def loadExtras(self, force=False):
		
		if not self.path in sys.path:
			sys.path.append(self.path)
		
		if force:
			for m in ['render', 'templatetags', 'hooks']:
				if m in sys.modules:
					del sys.modules[m]
		
		from extras import render
		from extras import templatetags
		from extras import hooks
		
		from django.template.loader import add_to_builtins
		add_to_builtins('extras.templatetags')
	
		global render, templatetags, hooks
Exemplo n.º 16
0
    def setup(self):
        """
        Configure django to use both our template and pages folder as locations
        to look for included templates.
        """

        settings = {
            "TEMPLATE_DIRS": [self.template_path, self.page_path],
            "INSTALLED_APPS": ['django.contrib.markup'],
        }

        if self.locale is not None:
            settings.update({
                "USE_I18N": True,
                "USE_L10N": False,
                "LANGUAGE_CODE":  self.locale,
                "LOCALE_PATHS": [self.locale_path],
            })

        django.conf.settings.configure(**settings)

        add_to_builtins('cactus.template_tags')
Exemplo n.º 17
0
# This app doesn't contain any models, but as its template tags need to
# be added to built-ins at start-up time, this is a good place to do it.

from django.template.loader import add_to_builtins

add_to_builtins("overextends.templatetags.overextends_tags")
Exemplo n.º 18
0
# components module
##
import components

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

# to enable insert_above stuff
# add_to_builtins has changed location with django-1.7
# also note this will probably go away some day
try:
    from django.template.loader import add_to_builtins
except:
    from django.template.base import add_to_builtins
add_to_builtins('insert_above.templatetags.insert_tags')

from settings import auxiliaries, INSTALLED_APPS

from unfold.loginrequired import LoginRequiredView

import portal.about
import portal.certificate
import portal.institution
import portal.registrationview
import portal.accountview
import portal.contactview
import portal.termsview
import portal.supportview
import portal.omn
Exemplo n.º 19
0
except ImportError:
    pass
else:
    try:
        attrlist = live_settings.__all__
    except AttributeError:
        attrlist = dir(live_settings)
    for attr in attrlist:
        if attr.startswith('__'):
            continue
        globals()[attr] = getattr(live_settings, attr)

try:
    from settings_local import *
except ImportError:
    pass


DATABASE_ENGINE = DATABASES['default']['ENGINE']

# This must go _after_ the cache backends are configured, which could be in
# local settings
from django.template.loader import add_to_builtins
add_to_builtins('cachebuster.templatetags.cachebuster')

if not DEBUG:
    # if not `running in runserver` would be a better condition here
    TEMPLATE_LOADERS = (
        ('django.template.loaders.cached.Loader', TEMPLATE_LOADERS),
    )
Exemplo n.º 20
0
from django.core.paginator import Paginator, Page
from django.template.loader import add_to_builtins

add_to_builtins('project.order.templatetags.mytagslib')


class PageMixin:
    def digg_page_range(self):
        page = self
        paginator = self.paginator

        BODY_PAGES = 5
        MARGIN_PAGES = 2
        TAIL_PAGES = 2

        position = 1

        p, q = TAIL_PAGES, max(
            1,
            min(page.number - BODY_PAGES / 2,
                paginator.num_pages - BODY_PAGES + 1))

        if q - p > MARGIN_PAGES:
            for x in xrange(position, p + 1):
                yield x

            yield None

            position = q

        p, q = q + BODY_PAGES - 1, paginator.num_pages - TAIL_PAGES + 1
Exemplo n.º 21
0
__autor__ = 'ahmetdal'

from django.conf import settings


CONTENT_TYPE_EXTERNAL_APP_LABEL = hasattr(settings, 'CONTENT_TYPE_EXTERNAL_APP_LABEL') and settings.CONTENT_TYPE_EXTERNAL_APP_LABEL or 'external'
PERMISSION_EXTERNAL_CODE_NAME = hasattr(settings, 'PERMISSION_EXTERNAL_CODE_NAME') and settings.CONTENT_TYPE_EXTERNAL_APP_LABEL or 'external'

DAW_LOAD_AS_BUILT_IN = hasattr(settings, 'DAW_LOAD_AS_BUILT_IN') and settings.DAW_LOAD_AS_BUILT_IN or True

if DAW_LOAD_AS_BUILT_IN:
    from django.template.loader import add_to_builtins

    add_to_builtins('daw.templatetags.on_approval_count')
    add_to_builtins('daw.templatetags.on_approval_objects')
    add_to_builtins('daw.templatetags.process_button_modals')
    add_to_builtins('daw.templatetags.process_buttons')
    add_to_builtins('daw.templatetags.content_type_filter')
Exemplo n.º 22
0
urlpatterns = patterns('',
    #url(r'^auth/', include('social_auth.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^movies/', include('apps.movies.urls')),
    url(r'^wishlist/', include('apps.wishlist.urls')),
    url(r'^groups/', include('apps.groups.urls')),
    url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}),
    url(r'^~', include('apps.profiles.urls')),
    # url(r'^social/', include('social_auth.urls' )),
    url('', include('social.apps.django_app.urls', namespace='social')),
    url(r'^$', HomeView.as_view(), name='home'),
)


# Static file handling for dev env
if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += patterns('',
            (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}),
    )



# Autoload template tags see AUTOLOAD_TEMPLATETAGS in settings
if hasattr(settings, 'AUTOLOAD_TEMPLATETAGS'):
    from django.template.loader import add_to_builtins
    for tag in settings.AUTOLOAD_TEMPLATETAGS:
        add_to_builtins(tag)

Exemplo n.º 23
0
# following PEP 386
__version__ = "1.1.1"

VERSION = (1, 1, 1)

# Make sure the ``{% print %}`` is always available, even without a {% load debug_tags %} call.
# **NOTE** this uses the undocumented, unofficial add_to_builtins() call. It's not promoted
# by Django developers because it's better to be explicit with a {% load .. %} in the templates.
#
# This function is used here nevertheless because the {% print %} tag is a debugging aid,
# and not a tag that should remain permanently in your templates. Convenience is preferred here.
#
from django.template.loader import add_to_builtins
add_to_builtins("debugtools.templatetags.debug_tags")
Exemplo n.º 24
0
import warnings
from django.template import Template, Context, loader
from django.test.client import RequestFactory

rf = RequestFactory()

# add activelink to builtin tags
loader.add_to_builtins('activelink.templatetags.activelink')


def render(template_string, dictionary=None):
    """Render a template from the supplied string, with optional context data."""
    context = Context(dictionary)
    return Template(template_string).render(context)


def test_ifactive():
    template = """{% ifactive "test" %}on{% else %}off{% endifactive %}"""

    data = {'request': rf.get('/test-url/')}
    rendered = render(template, data)
    assert rendered == 'on'

    data = {'request': rf.get('/not-test-url/')}
    rendered = render(template, data)
    assert rendered == 'off'


def test_ifactive_without_else():
    template = """{% ifactive "test" %}on{% endifactive %}"""
Exemplo n.º 25
0
import re
from django.conf.urls.defaults import url, patterns, include
from django.conf import settings
from django.contrib import admin
from django.template.loader import add_to_builtins
from django.views.generic import RedirectView, TemplateView

add_to_builtins('bootstrapform.templatetags.bootstrap')
add_to_builtins('avocado.templatetags.avocado_tags')

admin.autodiscover()

urlpatterns = patterns(
    '',

    # Landing page
    url(r'^$', RedirectView.as_view(url=settings.LOGIN_URL, permanent=True),
        name='landing'),

    # Cilantro Pages
    url(r'^workspace/', TemplateView.as_view(template_name='index.html'),
        name='workspace'),
    url(r'^query/', TemplateView.as_view(template_name='index.html'),
        name='query'),
    url(r'^results/', TemplateView.as_view(template_name='index.html'),
        name='results'),
    url(r'^analysis/', TemplateView.as_view(template_name='index.html'),
        name='analysis'),

    # Required for opening a sample
    url(r'^sample/', TemplateView.as_view(template_name='index.html'),
Exemplo n.º 26
0
def set_dynamic_settings(s):
    """
    Called at the end of the project's settings module and is passed
    its globals dict for updating with some final tweaks for settings
    that generally aren't specified but can be given some better
    defaults based on other settings that have been specified. Broken
    out into its own function so that the code need not be replicated
    in the settings modules of other project-based apps that leverage
    Mezzanine's settings module.
    """

    s["TEMPLATE_DEBUG"] = s["DEBUG"]
    add_to_builtins("mezzanine.template.loader_tags")
    # Define some settings based on management command being run.
    management_command = sys.argv[1] if len(sys.argv) > 1 else ""
    # Some kind of testing is running via test or testserver
    s["TESTING"] = management_command.startswith("test")
    # Some kind of development server is running via runserver or
    # runserver_plus
    s["DEV_SERVER"] = management_command.startswith("runserver")
    # Change INSTALLED_APPS to a list for easier manipulation.
    s["INSTALLED_APPS"] = list(s["INSTALLED_APPS"])

    # Set up cookie messaging if none specified for Django >= 1.3
    if VERSION >= (1, 3, 0):
        msg_mw = "django.contrib.messages.middleware.MessageMiddleware"
        if msg_mw not in s["MIDDLEWARE_CLASSES"]:
            s["MIDDLEWARE_CLASSES"] = tuple(s["MIDDLEWARE_CLASSES"])
            s["MIDDLEWARE_CLASSES"] += (msg_mw, )
        if not s.get("MESSAGE_STORAGE"):
            storage = "django.contrib.messages.storage.cookie.CookieStorage"
            s["MESSAGE_STORAGE"] = storage

    # Setup for optional apps.
    if not s["TESTING"]:
        optional = list(s.get("OPTIONAL_APPS", []))
        if s.get("USE_SOUTH"):
            optional.append("south")
        elif not s.get("USE_SOUTH", True) and "south" in s["INSTALLED_APPS"]:
            s["INSTALLED_APPS"].remove("south")
        for app in optional:
            if app not in s["INSTALLED_APPS"]:
                try:
                    __import__(app)
                except ImportError:
                    pass
                else:
                    s["INSTALLED_APPS"].append(app)

    if "debug_toolbar" in s["INSTALLED_APPS"]:
        debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
        if debug_mw not in s["MIDDLEWARE_CLASSES"]:
            s["MIDDLEWARE_CLASSES"] = tuple(s["MIDDLEWARE_CLASSES"])
            s["MIDDLEWARE_CLASSES"] += (debug_mw, )
    if s.get("PACKAGE_NAME_FILEBROWSER") in s["INSTALLED_APPS"]:
        s["FILEBROWSER_URL_FILEBROWSER_MEDIA"] = "/filebrowser/media/"
        fb_path = path_for_import(s["PACKAGE_NAME_FILEBROWSER"])
        fb_media_path = os.path.join(fb_path, "media", "filebrowser")
        s["FILEBROWSER_PATH_FILEBROWSER_MEDIA"] = fb_media_path
    grappelli_name = s.get("PACKAGE_NAME_GRAPPELLI")
    s["GRAPPELLI_INSTALLED"] = grappelli_name in s["INSTALLED_APPS"]
    if s["GRAPPELLI_INSTALLED"]:
        # Ensure Grappelli is after Mezzanine in app order so that
        # admin templates are loaded in the correct order.
        s["INSTALLED_APPS"].remove(grappelli_name)
        s["INSTALLED_APPS"].append(grappelli_name)
        s.setdefault("GRAPPELLI_ADMIN_HEADLINE", "Mezzanine")
        s.setdefault("GRAPPELLI_ADMIN_TITLE", "Mezzanine")
        grappelli_path = path_for_import(s["PACKAGE_NAME_GRAPPELLI"])
        s["GRAPPELLI_MEDIA_PATH"] = os.path.join(grappelli_path, "media")
        # Adopted from django.core.management.commands.runserver
        # Easiest way so far to actually get all the media for
        # Grappelli working with the dev server is to hard-code the
        # host:port to ADMIN_MEDIA_PREFIX, so here we check for a
        # custom host:port before doing this.
        if len(sys.argv) >= 2 and sys.argv[1] == "runserver":
            addrport = ""
            if len(sys.argv) > 2:
                addrport = sys.argv[2]
            if not addrport:
                addr, port = "", "8000"
            else:
                try:
                    addr, port = addrport.split(":")
                except ValueError:
                    addr, port = "", addrport
            if not addr:
                addr = "127.0.0.1"
            parts = (addr, port, s["ADMIN_MEDIA_PREFIX"])
            s["ADMIN_MEDIA_PREFIX"] = "http://%s:%s%s" % parts
    # Ensure admin is last in the app order so that admin templates
    # are loaded in the correct order.
    if "django.contrib.admin" in s["INSTALLED_APPS"]:
        s["INSTALLED_APPS"].remove("django.contrib.admin")
        s["INSTALLED_APPS"].append("django.contrib.admin")

    # Add missing apps if existing apps depend on them.
    if ("mezzanine.blog" in s["INSTALLED_APPS"]
            and "mezzanine.generic" not in s["INSTALLED_APPS"]):
        s["INSTALLED_APPS"].append("mezzanine.generic")
    if "mezzanine.generic" in s["INSTALLED_APPS"]:
        s["COMMENTS_APP"] = "mezzanine.generic"
        if "django.contrib.comments" not in s["INSTALLED_APPS"]:
            s["INSTALLED_APPS"].append("django.contrib.comments")

    # Change INSTALLED_APPS back to a tuple.
    s["INSTALLED_APPS"] = tuple(s["INSTALLED_APPS"])

    # Caching.
    if not (s.get("CACHE_BACKEND") or s.get("CACHES")):
        s["MIDDLEWARE_CLASSES"] = [
            mw for mw in s["MIDDLEWARE_CLASSES"]
            if not mw.endswith("UpdateCacheMiddleware")
            or mw.endswith("FetchFromCacheMiddleware")
        ]

    # Some settings tweaks for different DB engines.
    backend_path = "django.db.backends."
    backend_shortnames = (
        "postgresql_psycopg2",
        "postgresql",
        "mysql",
        "sqlite3",
        "oracle",
    )
    for (key, db) in s["DATABASES"].items():
        if db["ENGINE"] in backend_shortnames:
            s["DATABASES"][key]["ENGINE"] = backend_path + db["ENGINE"]
        shortname = db["ENGINE"].split(".")[-1]
        if shortname == "sqlite3" and os.sep not in db["NAME"]:
            # If the Sqlite DB name doesn't contain a path, assume
            # it's in the project directory and add the path to it.
            s["DATABASES"][key]["NAME"] = os.path.join(
                s.get("PROJECT_ROOT", ""), db["NAME"])
        elif shortname == "mysql":
            # Required MySQL collation for tests.
            s["DATABASES"][key]["TEST_COLLATION"] = "utf8_general_ci"
        elif shortname.startswith("postgresql") and not s.get("TIME_ZONE", 1):
            # Specifying a blank time zone to fall back to the
            # system's time zone will break table creation in Postgres
            # so remove it.
            del s["TIME_ZONE"]

    # If a theme is defined then add its template path to the
    # template dirs.
    theme = s.get("THEME")
    if theme:
        theme_templates = os.path.join(path_for_import(theme), "templates")
        s["TEMPLATE_DIRS"] = (theme_templates, ) + tuple(s["TEMPLATE_DIRS"])

    # Remaining code is for Django 1.1 support.
    if VERSION >= (1, 2, 0):
        return
    # Add the dummy csrf_token template tag to builtins and remove
    # Django's CsrfViewMiddleware.
    add_to_builtins("mezzanine.core.templatetags.dummy_csrf")
    s["MIDDLEWARE_CLASSES"] = [
        mw for mw in s["MIDDLEWARE_CLASSES"]
        if mw != "django.middleware.csrf.CsrfViewMiddleware"
    ]
    # Use the single DB settings.
    old_db_settings_mapping = {
        "ENGINE": "DATABASE_ENGINE",
        "HOST": "DATABASE_HOST",
        "NAME": "DATABASE_NAME",
        "OPTIONS": "DATABASE_OPTIONS",
        "PASSWORD": "******",
        "PORT": "DATABASE_PORT",
        "USER": "******",
        "TEST_CHARSET": "TEST_DATABASE_CHARSET",
        "TEST_COLLATION": "TEST_DATABASE_COLLATION",
        "TEST_NAME": "TEST_DATABASE_NAME",
    }
    for (new_name, old_name) in old_db_settings_mapping.items():
        value = s["DATABASES"]["default"].get(new_name)
        if value is not None:
            if new_name == "ENGINE" and value.startswith(backend_path):
                value = value.replace(backend_path, "", 1)
            s[old_name] = value

    # Revert to some old names.
    processors = list(s["TEMPLATE_CONTEXT_PROCESSORS"])
    for (i, processor) in enumerate(processors):
        if processor == "django.contrib.auth.context_processors.auth":
            processors[i] = "django.core.context_processors.auth"
    s["TEMPLATE_CONTEXT_PROCESSORS"] = processors
    loaders = list(s["TEMPLATE_LOADERS"])
    for (i, loader) in enumerate(loaders):
        if loader.startswith("django.") and loader.endswith(".Loader"):
            loaders[i] = loader.replace(".Loader", ".load_template_source", 1)
    s["TEMPLATE_LOADERS"] = loaders
Exemplo n.º 27
0
from google.appengine.api import memcache
##import app.webapp as webapp2
from django.template import TemplateDoesNotExist
from django.conf import settings
settings._target = None
#from model import g_blog,User
#activate(g_blog.language)
from google.appengine.api import taskqueue
from mimetypes import types_map
from datetime import datetime
import urllib
import traceback

from django.template.loader import add_to_builtins

add_to_builtins('app.filter')
add_to_builtins('app.recurse')
import micolog_template

logging.info('module base reloaded')


def urldecode(value):
    return urllib.unquote(urllib.unquote(value)).decode('utf8')
    #return  urllib.unquote(value).decode('utf8')


def urlencode(value):
    return urllib.quote(value.encode('utf8'))

Exemplo n.º 28
0
        super(ModelEx, self).__init__(*args, **kwargs)
        self.remember_original()

    def save(self, *args, **kwargs):
        super(ModelEx, self).save(*args, **kwargs)
        self.remember_original()

    def remember_original(self):
        """
            Mechanism used to check whether a certain field has been changed.
            http://stackoverflow.com/a/1793323/2203044

            Override to remember here the original values of all the fields
            you want.

            This way, together with signals, you can easily implement cache
            invalidation. Of course, the method is limited to signal limits
            (e.g. filter().update() won't send signals)

            Use _original_ prefix for all those fields.

            For example:
                self._original_hidden = self.hidden
        """
        # Empty by default...
        pass

# ovo navodno nije preporuceno, ali vjerujem da ce se
# dovoljno cesto koristiti da DRY nadjaca
add_to_builtins('libs.templatetags.libs_tags')
Exemplo n.º 29
0
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}



# Configuracion de registration
ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value.
LOGIN_REDIRECT_URL = '/accounts/login/'
REGISTRATION_OPEN = False

# Add Builtin Template Tags
from django.template.loader import add_to_builtins
add_to_builtins('django.templatetags.static')
Exemplo n.º 30
0
from django.template.loader import add_to_builtins
add_to_builtins('conditionalblock.templatetags.conditionalblock')
Exemplo n.º 31
0
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from django.template.loader import add_to_builtins
add_to_builtins('plugins.template_tags')
Exemplo n.º 32
0
import fields, views, urls, models, widgets

try:
    from django.template.loader import add_to_builtins
except:
    from django.template.base import add_to_builtins

add_to_builtins('ckeditor_filer.templatetags.ckeditor_tags')
Exemplo n.º 33
0
from django import template
from django.template.loader import add_to_builtins


register = template.Library()

@register.filter(name='classname')
def classname(obj):
	classname = obj.__class__.__name__
	return classname

add_to_builtins('website.templatetags.extra_tags')
Exemplo n.º 34
0
# -----------------------------------------------
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': ensure_exists(environment('tmp', 'cache')),
    }
}


# Extra built-in template-tags
# -----------------------------------------------
EXTRA_BUILTIN_TEMPLATETAGS = (
    'lib.templatetags.onload_handlers',
)
for builtin in EXTRA_BUILTIN_TEMPLATETAGS:
    add_to_builtins(builtin)


# Logging settings
# -----------------------------------------------
def logging_filename():
    logdir = os.path.join(ENV_ROOT, 'logs')
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    return os.path.join(logdir, '%s.log' % PROJECT_MODULE)
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': ('%(levelname)s %(asctime)s |'
Exemplo n.º 35
0
CONVERSATION_TYPES = [
    ("email", "Email"),
    ("phone", "Phone Call"),
    ("in-person", "In-Person"),
    ("mail", "Postal Mail"),
    ("online", "Online"),
]

GIST_LENGTH = 200
MORE_CONVERSATIONS_SIZE = 10

from django.template.loader import add_to_builtins
add_to_builtins('compressor.templatetags.compress')
Exemplo n.º 36
0
def set_dynamic_settings(s):
    """
    Called at the end of the project's settings module and is passed its 
    globals dict for updating with some final tweaks for settings that 
    generally aren't specified but can be given some better defaults based on 
    other settings that have been specified. Broken out into its own 
    function so that the code need not be replicated in the settings modules 
    of other project-based apps that leverage Mezzanine's settings module.
    """

    s["TEMPLATE_DEBUG"] = s["DEBUG"]
    add_to_builtins("mezzanine.template.loader_tags")
    # Define some settings based on management command being run.
    management_command = sys.argv[1] if len(sys.argv) > 1 else ""
    # Some kind of testing is running via test or testserver
    s["TESTING"] = management_command.startswith("test")
    # Some kind of development server is running via runserver or runserver_plus
    s["DEV_SERVER"] = management_command.startswith("runserver")
    # Change INSTALLED_APPS to a list for easier manipulation.
    s["INSTALLED_APPS"] = list(s["INSTALLED_APPS"])

    # Setup for optional apps.
    if not s["TESTING"]:
        for app in s.get("OPTIONAL_APPS", []):
            if app not in s["INSTALLED_APPS"]:
                try:
                    __import__(app)
                except ImportError:
                    pass
                else:
                    s["INSTALLED_APPS"].append(app)

    if "debug_toolbar" in s["INSTALLED_APPS"]:
        debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
        if debug_mw not in s["MIDDLEWARE_CLASSES"]:
            s["MIDDLEWARE_CLASSES"] = tuple(s["MIDDLEWARE_CLASSES"])
            s["MIDDLEWARE_CLASSES"] += (debug_mw,)
    if s.get("PACKAGE_NAME_FILEBROWSER") in s["INSTALLED_APPS"]:
        s["FILEBROWSER_URL_FILEBROWSER_MEDIA"] = "/filebrowser/media/"
        fb_path = path_for_import(s["PACKAGE_NAME_FILEBROWSER"])
        fb_media_path = os.path.join(fb_path, "media", "filebrowser")
        s["FILEBROWSER_PATH_FILEBROWSER_MEDIA"] = fb_media_path
    grappelli_name = s.get("PACKAGE_NAME_GRAPPELLI")
    s["GRAPPELLI_INSTALLED"] = grappelli_name in s["INSTALLED_APPS"]
    if s["GRAPPELLI_INSTALLED"]:
        # Ensure Grappelli is after Mezzanine in app order so that 
        # admin templates are loaded in the correct order.
        s["INSTALLED_APPS"].remove(grappelli_name)
        s["INSTALLED_APPS"].append(grappelli_name)
        s["GRAPPELLI_ADMIN_HEADLINE"] = "Mezzanine"
        s["GRAPPELLI_ADMIN_TITLE"] = "Mezzanine"
        grappelli_path = path_for_import(s["PACKAGE_NAME_GRAPPELLI"])
        s["GRAPPELLI_MEDIA_PATH"] = os.path.join(grappelli_path, "media")
        # Adopted from django.core.management.commands.runserver
        # Easiest way so far to actually get all the media for Grappelli 
        # working with the dev server is to hard-code the host:port to 
        # ADMIN_MEDIA_PREFIX, so here we check for a custom host:port 
        # before doing this.
        if len(sys.argv) >= 2 and sys.argv[1] == "runserver":
            addrport = ""
            if len(sys.argv) > 2:
                addrport = sys.argv[2]
            if not addrport:
                addr, port = "", "8000"
            else:
                try:
                    addr, port = addrport.split(":")
                except ValueError:
                    addr, port = "", addrport
            if not addr:
                addr = "127.0.0.1"
            parts = (addr, port, s["ADMIN_MEDIA_PREFIX"])
            s["ADMIN_MEDIA_PREFIX"] = "http://%s:%s%s" % parts
    # Ensure admin is last in the app order so that admin templates 
    # are loaded in the correct order.
    if "django.contrib.admin" in s["INSTALLED_APPS"]:
        s["INSTALLED_APPS"].remove("django.contrib.admin")
        s["INSTALLED_APPS"].append("django.contrib.admin")
    # Change INSTALLED_APPS back to a tuple.
    s["INSTALLED_APPS"] = tuple(s["INSTALLED_APPS"])

    # Caching.
    if not (s.get("CACHE_BACKEND") or s.get("CACHES")):
        s["MIDDLEWARE_CLASSES"] = [mw for mw in s["MIDDLEWARE_CLASSES"] if not
                                   mw.endswith("UpdateCacheMiddleware") or 
                                   mw.endswith("FetchFromCacheMiddleware")]

    # Some settings tweaks for different DB engines.
    backend_path = "django.db.backends."
    backend_shortnames = (
        "postgresql_psycopg2",
        "postgresql",
        "mysql",
        "sqlite3",
        "oracle",
    )
    for (key, db) in s["DATABASES"].items():
        if db["ENGINE"] in backend_shortnames:
            s["DATABASES"][key]["ENGINE"] = backend_path + db["ENGINE"]
        shortname = db["ENGINE"].split(".")[-1]
        if shortname == "sqlite3" and os.sep not in db["NAME"]:
            # If the Sqlite DB name doesn't contain a path, assume it's 
            # in the project directory and add the path to it.
            s["DATABASES"][key]["NAME"] = os.path.join(
                                     s.get("PROJECT_ROOT", ""), db["NAME"])
        elif shortname == "mysql":
            # Required MySQL collation for tests.
            s["DATABASES"][key]["TEST_COLLATION"] = "utf8_general_ci"
        elif shortname.startswith("postgresql") and not s.get("TIME_ZONE", 1):
            # Specifying a blank time zone to fall back to the system's 
            # time zone will break table creation in Postgres so remove it.
            del s["TIME_ZONE"]

    # If a theme is defined then add its template path to the template dirs.
    theme = s.get("THEME")
    if theme:
        theme_templates = os.path.join(path_for_import(theme), "templates")
        s["TEMPLATE_DIRS"] = (theme_templates,) + tuple(s["TEMPLATE_DIRS"])
        
    # Remaining code is for Django 1.1 support.
    if VERSION >= (1, 2, 0):
        return
    # Add the dummy csrf_token template tag to builtins and remove 
    # Django's CsrfViewMiddleware.
    add_to_builtins("mezzanine.core.templatetags.dummy_csrf")
    s["MIDDLEWARE_CLASSES"] = [mw for mw in s["MIDDLEWARE_CLASSES"] if 
                        mw != "django.middleware.csrf.CsrfViewMiddleware"]
    # Use the single DB settings.
    old_db_settings_mapping = {
        "ENGINE": "DATABASE_ENGINE",
        "HOST": "DATABASE_HOST",
        "NAME": "DATABASE_NAME",
        "OPTIONS": "DATABASE_OPTIONS",
        "PASSWORD": "******",
        "PORT": "DATABASE_PORT",
        "USER": "******",
        "TEST_CHARSET": "TEST_DATABASE_CHARSET",
        "TEST_COLLATION": "TEST_DATABASE_COLLATION",
        "TEST_NAME": "TEST_DATABASE_NAME",
    }
    for (new_name, old_name) in old_db_settings_mapping.items():
        value = s["DATABASES"]["default"].get(new_name)
        if value is not None:
            if new_name == "ENGINE" and value.startswith(backend_path):
                value = value.replace(backend_path, "", 1)
            s[old_name] = value
    
    # Revert to some old names.
    processors = list(s["TEMPLATE_CONTEXT_PROCESSORS"])
    for (i, processor) in enumerate(processors):
        if processor == "django.contrib.auth.context_processors.auth":
            processors[i] = "django.core.context_processors.auth"
    s["TEMPLATE_CONTEXT_PROCESSORS"] = processors
    loaders = list(s["TEMPLATE_LOADERS"])
    for (i, loader) in enumerate(loaders):
        if loader.startswith("django.") and loader.endswith(".Loader"):
            loaders[i] = loader.replace(".Loader", ".load_template_source", 1)
    s["TEMPLATE_LOADERS"] = loaders
Exemplo n.º 37
0
    second_slash_index = path.find('/', 1)
    if second_slash_index == -1:
        mainnav = path[1:]
    else:
        mainnav = path[1:second_slash_index]
    return {'mainnav': mainnav}


def _get_context_username(request):
    context_username = ''
    path = request.path
    if path == '' or path == '/':
        return context_username
    second_slash_index = path.find('/', 1)
    if second_slash_index == -1:
        context_username = path[1:]
    else:
        context_username = path[1:second_slash_index]
    return context_username


def __cache_version_update(sender, **kwargs):
    da_post_save(kwargs['instance'])


from django.template.loader import add_to_builtins
add_to_builtins('gitshell.viewtools.templatetags.gstools')

post_save.connect(__cache_version_update)
post_delete.connect(__cache_version_update)
Exemplo n.º 38
0
    live_settings = imp.load_module(module_name, *module_info)
except ImportError:
    pass
else:
    try:
        attrlist = live_settings.__all__
    except AttributeError:
        attrlist = dir (live_settings)
    for attr in attrlist:
        if attr.startswith('__'):
            continue
        globals()[attr] = getattr (live_settings, attr)

try:
    from settings_local import *
except ImportError:
    pass

DATABASE_ENGINE = DATABASES['default']['ENGINE']

# This must go _after_ the cache backends are configured, which could be in
# local settings
from django.template.loader import add_to_builtins
add_to_builtins('cachebuster.templatetags.cachebuster')

if not DEBUG:
    # if not `running in runserver` would be a better condition here
    TEMPLATE_LOADERS = (
            ('django.template.loaders.cached.Loader', TEMPLATE_LOADERS),
            )
Exemplo n.º 39
0
    viewdata = {'urlexamples': urlconf.urlexamples}
    return render_to_response(request, "builtin/index.html", viewdata=viewdata)


def manual(request):
    return render_to_response(request, "builtin/manual.html")


# patch Django url reverse
_django_reverse = None


def _reverse(*args, **kwargs):
    try:
        url = _django_reverse(*args, **kwargs)
    except NoReverseMatch:
        url = "NoReverseMatch"
    return url


def _patch_reverse():
    global _django_reverse
    if urlresolvers.reverse is not _reverse:
        _django_reverse = urlresolvers.reverse
        urlresolvers.reverse = _reverse


_patch_reverse()

add_to_builtins('littlepony.templatetags.stubs')
Exemplo n.º 40
0
from django.views.static import serve
from django.conf import settings
from django.template.loader import add_to_builtins

from freenasUI import freeadmin
from freenasUI.freeadmin.site import site
from freenasUI.freeadmin.middleware import public
from freenasUI.freeadmin.navtree import navtree

handler500 = 'freenasUI.freeadmin.views.server_error'
handler404 = 'freenasUI.freeadmin.views.page_not_found'

navtree.prepare_modelforms()
freeadmin.autodiscover()

add_to_builtins('django.templatetags.i18n')

urlpatterns = patterns(
    '',
    url('^$', site.adminInterface, name="index"),
    (r'^reporting/graphs/(?P<path>.*)', public(serve), {
        'document_root': '/var/db/graphs/'
    }),
    (r'^media/(?P<path>.*)', public(serve), {
        'document_root': settings.MEDIA_ROOT
    }),
    (r'^static/(?P<path>.*)', public(serve), {
        'document_root': os.path.join(settings.HERE, "freeadmin/static")
    }),
    (r'^dojango/dojo-media/release/[^/]+/(?P<path>.*)$', public(serve), {
        'document_root': '/usr/local/www/dojo'
Exemplo n.º 41
0
def set_dynamic_settings(s):
    """
    Called at the end of the project's settings module, and is passed
    its globals dict for updating with some final tweaks for settings
    that generally aren't specified, but can be given some better
    defaults based on other settings that have been specified. Broken
    out into its own function so that the code need not be replicated
    in the settings modules of other project-based apps that leverage
    Mezzanine's settings module.
    """

    # Moves an existing list setting value to a different position.
    move = lambda n, k, i: s[n].insert(i, s[n].pop(s[n].index(k)))
    # Add a value to the end of a list setting if not in the list.
    append = lambda n, k: s[n].append(k) if k not in s[n] else None
    # Add a value to the start of a list setting if not in the list.
    prepend = lambda n, k: s[n].insert(0, k) if k not in s[n] else None
    # Remove a value from a list setting if in the list.
    remove = lambda n, k: s[n].remove(k) if k in s[n] else None

    s["TEMPLATE_DEBUG"] = s.get("TEMPLATE_DEBUG", s.get("DEBUG", False))
    add_to_builtins("mezzanine.template.loader_tags")
    # Define some settings based on management command being run.
    management_command = sys.argv[1] if len(sys.argv) > 1 else ""
    # Some kind of testing is running via test or testserver.
    s["TESTING"] = management_command.startswith("test")
    # Some kind of development server is running via runserver,
    # runserver_plus or harvest (lettuce)
    s["DEV_SERVER"] = management_command.startswith("runserver") or \
                      management_command == "harvest"
    # Change tuple settings to lists for easier manipulation.
    s["INSTALLED_APPS"] = list(s["INSTALLED_APPS"])
    s["MIDDLEWARE_CLASSES"] = list(s["MIDDLEWARE_CLASSES"])
    s["STATICFILES_FINDERS"] = list(
        s.get("STATICFILES_FINDERS", STATICFILES_FINDERS))

    if s["DEV_SERVER"]:
        s["STATICFILES_DIRS"] = list(s.get("STATICFILES_DIRS", []))
        s["STATICFILES_DIRS"].append(s.pop("STATIC_ROOT"))

    # Set up cookie messaging if none defined.
    storage = "django.contrib.messages.storage.cookie.CookieStorage"
    s.setdefault("MESSAGE_STORAGE", storage)

    if s["TESTING"]:
        # Enable accounts when testing so the URLs exist.
        append("INSTALLED_APPS", "mezzanine.accounts")
    else:
        # Setup for optional apps.
        optional = list(s.get("OPTIONAL_APPS", []))
        if s.get("USE_SOUTH"):
            optional.append("south")
        elif not s.get("USE_SOUTH", True) and "south" in s["INSTALLED_APPS"]:
            s["INSTALLED_APPS"].remove("south")
        for app in optional:
            if app not in s["INSTALLED_APPS"]:
                try:
                    __import__(app)
                except ImportError:
                    pass
                else:
                    s["INSTALLED_APPS"].append(app)
    if "debug_toolbar" in s["INSTALLED_APPS"]:
        debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
        prepend("MIDDLEWARE_CLASSES", debug_mw)
    if "compressor" in s["INSTALLED_APPS"]:
        append("STATICFILES_FINDERS", "compressor.finders.CompressorFinder")

    # Ensure the Mezzanine auth backend is enabled if
    # mezzanine.accounts is being used.
    if "mezzanine.accounts" in s["INSTALLED_APPS"]:
        auth_backend = "mezzanine.core.auth_backends.MezzanineBackend"
        s.setdefault("AUTHENTICATION_BACKENDS", [])
        prepend("AUTHENTICATION_BACKENDS", auth_backend)

    # Ensure Grappelli is after Mezzanine in app order so that
    # admin templates are loaded in the correct order.
    grappelli_name = s.get("PACKAGE_NAME_GRAPPELLI")
    try:
        move("INSTALLED_APPS", grappelli_name, len(s["INSTALLED_APPS"]))
    except ValueError:
        s["GRAPPELLI_INSTALLED"] = False
        s["ADMIN_MEDIA_PREFIX"] = s["STATIC_URL"] + "admin/"
    else:
        s["GRAPPELLI_INSTALLED"] = True
        s.setdefault("GRAPPELLI_ADMIN_HEADLINE", "Mezzanine")
        s.setdefault("GRAPPELLI_ADMIN_TITLE", "Mezzanine")

    # Ensure admin is last in the app order so that admin templates
    # are loaded in the correct order.
    move("INSTALLED_APPS", "django.contrib.admin", len(s["INSTALLED_APPS"]))

    # Add missing apps if existing apps depend on them.
    if "mezzanine.blog" in s["INSTALLED_APPS"]:
        append("INSTALLED_APPS", "mezzanine.generic")
    if "mezzanine.generic" in s["INSTALLED_APPS"]:
        s.setdefault("COMMENTS_APP", "mezzanine.generic")
        append("INSTALLED_APPS", "django.contrib.comments")

    # Ensure mezzanine.boot is first.
    try:
        move("INSTALLED_APPS", "mezzanine.boot", 0)
    except ValueError:
        pass

    # Remove caching middleware if no backend defined.
    if not (s.get("CACHE_BACKEND") or s.get("CACHES")):
        s["MIDDLEWARE_CLASSES"] = [
            mw for mw in s["MIDDLEWARE_CLASSES"]
            if not (mw.endswith("UpdateCacheMiddleware")
                    or mw.endswith("FetchFromCacheMiddleware"))
        ]

    # Some settings tweaks for different DB engines.
    for (key, db) in s["DATABASES"].items():
        shortname = db["ENGINE"].split(".")[-1]
        if shortname == "sqlite3" and os.sep not in db["NAME"]:
            # If the Sqlite DB name doesn't contain a path, assume
            # it's in the project directory and add the path to it.
            db_path = os.path.join(s.get("PROJECT_ROOT", ""), db["NAME"])
            s["DATABASES"][key]["NAME"] = db_path
        elif shortname == "mysql":
            # Required MySQL collation for tests.
            s["DATABASES"][key]["TEST_COLLATION"] = "utf8_general_ci"

    # Remaining is for Django < 1.4
    from django import VERSION
    if VERSION >= (1, 4):
        return
    s["TEMPLATE_CONTEXT_PROCESSORS"] = list(s["TEMPLATE_CONTEXT_PROCESSORS"])
    remove("TEMPLATE_CONTEXT_PROCESSORS", "django.core.context_processors.tz")
Exemplo n.º 42
0
Arquivo: urls.py Projeto: eteks/Adjod
from django.utils.translation import ugettext_lazy as _
from django.conf.urls.defaults import handler404, handler500
from paypal.standard.ipn import *

admin.autodiscover()

js_info_dict = {
    'packages': ('adjod', ),
}

#For Django chat
from chat.views import *

#For loading global functions
from django.template.loader import add_to_builtins
add_to_builtins('advertisement.templatetags.app_filters')

urlpatterns = patterns(
    '',
    url(r'^(?i)admin/', include(admin.site.urls)),
    url(r'^$', 'adjod.views.home', name='home'),

    # Home page URL
    url(r'^home/$', 'adjod.views.home', name='home'),

    # URL for enter post form page
    url(r'^postad/$', 'advertisement.views.product_form', name='product_form'),

    # User login verfication
    url(r'^login/$', 'adjod.views.user_login', name='user_login'),
Exemplo n.º 43
0
from django.template.loader import add_to_builtins
add_to_builtins('django.contrib.staticfiles.templatetags.staticfiles')
add_to_builtins('django.templatetags.i18n')
add_to_builtins('django.templatetags.future')
Exemplo n.º 44
0
def set_dynamic_settings(s):
    """
    Called at the end of the project's settings module, and is passed
    its globals dict for updating with some final tweaks for settings
    that generally aren't specified, but can be given some better
    defaults based on other settings that have been specified. Broken
    out into its own function so that the code need not be replicated
    in the settings modules of other project-based apps that leverage
    Mezzanine's settings module.
    """

    # Moves an existing list setting value to a different position.
    move = lambda n, k, i: s[n].insert(i, s[n].pop(s[n].index(k)))
    # Add a value to the end of a list setting if not in the list.
    append = lambda n, k: s[n].append(k) if k not in s[n] else None
    # Add a value to the start of a list setting if not in the list.
    prepend = lambda n, k: s[n].insert(0, k) if k not in s[n] else None
    # Remove a value from a list setting if in the list.
    remove = lambda n, k: s[n].remove(k) if k in s[n] else None

    s["TEMPLATE_DEBUG"] = s.get("TEMPLATE_DEBUG", s.get("DEBUG", False))
    add_to_builtins("mezzanine.template.loader_tags")

    if not s.get("ALLOWED_HOSTS", []):
        from warnings import warn
        warn("You haven't defined the ALLOWED_HOSTS settings, which "
             "Django 1.5 requires. Will fall back to the domains "
             "configured as sites.")
        s["ALLOWED_HOSTS"] = SitesAllowedHosts()

    # Define some settings based on management command being run.
    management_command = sys.argv[1] if len(sys.argv) > 1 else ""
    # Some kind of testing is running via test or testserver.
    s["TESTING"] = management_command in ("test", "testserver")
    # Some kind of development server is running via runserver,
    # runserver_plus or harvest (lettuce)
    s["DEV_SERVER"] = management_command.startswith(("runserver", "harvest"))

    # Change tuple settings to lists for easier manipulation.
    s.setdefault("AUTHENTICATION_BACKENDS", defaults.AUTHENTICATION_BACKENDS)
    s.setdefault("STATICFILES_FINDERS", defaults.STATICFILES_FINDERS)
    tuple_list_settings = ("AUTHENTICATION_BACKENDS", "INSTALLED_APPS",
                           "MIDDLEWARE_CLASSES", "STATICFILES_FINDERS")
    for setting in tuple_list_settings:
        s[setting] = list(s[setting])

    # Set up cookie messaging if none defined.
    storage = "django.contrib.messages.storage.cookie.CookieStorage"
    s.setdefault("MESSAGE_STORAGE", storage)

    if s["TESTING"]:
        # Following bits are work-arounds for some assumptions that
        # Django 1.5's tests make.

        # contrib.auth tests fail without its own auth backend installed.
        append("AUTHENTICATION_BACKENDS",
               "django.contrib.auth.backends.ModelBackend")

        # Tests in contrib.redirects simply don't work with a
        # catch-all urlpattern such as Mezzanine's pages app.
        remove("INSTALLED_APPS", "django.contrib.redirects")
        remove(
            "MIDDLEWARE_CLASSES",
            "django.contrib.redirects.middleware.RedirectFallbackMiddleware")

    else:
        # Setup for optional apps.
        optional = list(s.get("OPTIONAL_APPS", []))
        if s.get("USE_SOUTH"):
            optional.append("south")
        elif not s.get("USE_SOUTH", True) and "south" in s["INSTALLED_APPS"]:
            s["INSTALLED_APPS"].remove("south")
        for app in optional:
            if app not in s["INSTALLED_APPS"]:
                try:
                    __import__(app)
                except ImportError:
                    pass
                else:
                    s["INSTALLED_APPS"].append(app)
    if "debug_toolbar" in s["INSTALLED_APPS"]:
        debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
        prepend("MIDDLEWARE_CLASSES", debug_mw)
    # If compressor installed, ensure it's configured and make
    # Mezzanine's settings available to its offline context,
    # since jQuery is configured via a setting.
    if "compressor" in s["INSTALLED_APPS"]:
        append("STATICFILES_FINDERS", "compressor.finders.CompressorFinder")
        s.setdefault(
            "COMPRESS_OFFLINE_CONTEXT", {
                "MEDIA_URL": s.get("MEDIA_URL", ""),
                "STATIC_URL": s.get("STATIC_URL", ""),
            })

        def mezzanine_settings():
            from mezzanine.conf import settings
            return settings

        s["COMPRESS_OFFLINE_CONTEXT"]["settings"] = mezzanine_settings

    # Ensure the Mezzanine auth backend is enabled if
    # mezzanine.accounts is being used.
    if "mezzanine.accounts" in s["INSTALLED_APPS"]:
        auth_backend = "mezzanine.core.auth_backends.MezzanineBackend"
        s.setdefault("AUTHENTICATION_BACKENDS", [])
        prepend("AUTHENTICATION_BACKENDS", auth_backend)

    # Ensure Grappelli is after Mezzanine in app order so that
    # admin templates are loaded in the correct order.
    grappelli_name = s.get("PACKAGE_NAME_GRAPPELLI")
    try:
        move("INSTALLED_APPS", grappelli_name, len(s["INSTALLED_APPS"]))
    except ValueError:
        s["GRAPPELLI_INSTALLED"] = False
    else:
        s["GRAPPELLI_INSTALLED"] = True
        s.setdefault("GRAPPELLI_ADMIN_HEADLINE", "Mezzanine")
        s.setdefault("GRAPPELLI_ADMIN_TITLE", "Mezzanine")

    # Ensure admin is last in the app order so that admin templates
    # are loaded in the correct order.
    move("INSTALLED_APPS", "django.contrib.admin", len(s["INSTALLED_APPS"]))

    # Add missing apps if existing apps depend on them.
    if "mezzanine.blog" in s["INSTALLED_APPS"]:
        append("INSTALLED_APPS", "mezzanine.generic")
    if "mezzanine.generic" in s["INSTALLED_APPS"]:
        s.setdefault("COMMENTS_APP", "mezzanine.generic")
        append("INSTALLED_APPS", "django.contrib.comments")

    # Ensure mezzanine.boot is first.
    try:
        move("INSTALLED_APPS", "mezzanine.boot", 0)
    except ValueError:
        pass

    # Remove caching middleware if no backend defined.
    if not (s.get("CACHE_BACKEND") or s.get("CACHES")):
        s["MIDDLEWARE_CLASSES"] = [
            mw for mw in s["MIDDLEWARE_CLASSES"]
            if not (mw.endswith("UpdateCacheMiddleware")
                    or mw.endswith("FetchFromCacheMiddleware"))
        ]

    # Revert tuple settings back to tuples.
    for setting in tuple_list_settings:
        s[setting] = tuple(s[setting])

    # Some settings tweaks for different DB engines.
    for (key, db) in s["DATABASES"].items():
        shortname = db["ENGINE"].split(".")[-1]
        if shortname == "sqlite3" and os.sep not in db["NAME"]:
            # If the Sqlite DB name doesn't contain a path, assume
            # it's in the project directory and add the path to it.
            db_path = os.path.join(s.get("PROJECT_ROOT", ""), db["NAME"])
            s["DATABASES"][key]["NAME"] = db_path
        elif shortname == "mysql":
            # Required MySQL collation for tests.
            s["DATABASES"][key]["TEST_COLLATION"] = "utf8_general_ci"
Exemplo n.º 45
0
try:
    from django.template.loader import add_to_builtins
except:
    from django.template.base import add_to_builtins


add_to_builtins('ckeditor_filer.templatetags.ckeditor_tags')
Exemplo n.º 46
0
import os.path
import logging

from django import template
from django.template.loader import add_to_builtins

ROOT_PATH = os.path.abspath(os.path.dirname(__file__))

add_to_builtins('templating.templating')
add_to_builtins('templating.dnzo_templating')

TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.request',
    'cluster_project.webapp.context_processors.constants',
)

TEMPLATE_DIRS = (ROOT_PATH + '/resources/templates', )
Exemplo n.º 47
0
# -*- coding: utf-8 -*-
from hashlib import md5

from lxml.html import fragment_fromstring, fromstring

import django
from django.core.cache import cache
from django.template import Template, Context, loader
from django.test.client import RequestFactory
from django.utils.translation import get_language

from django_activeurl import settings
from django_activeurl.utils import ImproperlyConfigured


loader.add_to_builtins('django_activeurl.templatetags.activeurl')


requests = RequestFactory()


def render(template, context=None):
    context = Context(context)
    return Template(template).render(context)


def test_basic():
    template = '''
        {% activeurl %}
            <ul>
                <li>
Exemplo n.º 48
0
# -*- coding: utf-8; -*-
#
# Licensed to Crate (https://crate.io) under one or more contributor
# license agreements.  See the NOTICE file distributed with this work for
# additional information regarding copyright ownership.  Crate licenses
# this file to you 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.
#
# However, if you have executed another commercial license agreement
# with Crate these terms will supersede the license and you may use the
# software solely pursuant to the terms of the relevant commercial agreement.

__docformat__ = "reStructuredText"

from django.template.loader import add_to_builtins

# register filters
add_to_builtins('web.filters')
# register tags
add_to_builtins('web.tags')
Exemplo n.º 49
0
from django.template.loader import add_to_builtins

add_to_builtins('audio.templatetags.verbatim')
Exemplo n.º 50
0
# vim: set fileencodings=utf-8
# -*- coding: utf-8 -*-

__docformat__ = "reStructuredText"

from django.template.loader import add_to_builtins

# register filters
add_to_builtins('web.filters')
# register tags
add_to_builtins('web.tags')
Exemplo n.º 51
0
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.redirects.middleware.RedirectFallbackMiddleware",
    "django.middleware.cache.UpdateCacheMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.cache.FetchFromCacheMiddleware",
    "mezzanine.core.middleware.MobileTemplate",
    "mezzanine.core.middleware.AdminLoginInterfaceSelector",
)

# For > Django 1.2 add the CSRF middleware. For earlier, add the dummy
# csrf_token template tag to builtins.
from django import VERSION
if VERSION[0] <= 1 and VERSION[1] <= 1:
    from django.template.loader import add_to_builtins
    add_to_builtins("mezzanine.core.templatetags.dummy_csrf")
else:
    MIDDLEWARE_CLASSES += ("django.middleware.csrf.CsrfViewMiddleware",)

# Store these package names here as they may change in the future since at the
# moment we are using custom forks of them.
PACKAGE_NAME_FILEBROWSER = "filebrowser_safe"
PACKAGE_NAME_GRAPPELLI = "grappelli_safe"

# Optional apps.
OPTIONAL_APPS = (
    "debug_toolbar",
    "south",
    "django_extensions",
    PACKAGE_NAME_FILEBROWSER,
    PACKAGE_NAME_GRAPPELLI,
Exemplo n.º 52
0
try:
    shutil.rmtree(settings.BUILD_DIR)
except OSError:
    pass

base_template_dirs = (
    '',
    'documentation/',
)

os.mkdir(settings.BUILD_DIR)

content_files = []

loader.add_to_builtins('generator.templatetags.extras')

for root, dirnames, filenames in os.walk(settings.CONTENT_DIR):
    for dirname in dirnames:
        dir_path = os.path.join(root, dirname)
        os.mkdir(get_build_path(dir_path))

    # Figure out the files in this dir (the build dir)
    html_files = [filename + '.html' for filename in filenames]

    for filename in filenames:
        data['dirnames'] = dirnames
        file_path = os.path.join(root, filename)
        relative_path = remove_content_dir(file_path)
        data['relative_path'] = relative_path
Exemplo n.º 53
0
from .templatetags.spurl import convert_to_boolean
import nose

# This file acts as a urlconf
urlpatterns = patterns('',
    url('^test/$', lambda r: HttpResponse('ok'), name='test')
)

# bootstrap django
settings.configure(
    ROOT_URLCONF='spurl.tests',
    INSTALLED_APPS=['spurl.tests'],
)

# add spurl to builtin tags
loader.add_to_builtins('spurl.templatetags.spurl')

def render(template_string, dictionary=None, autoescape=False):
    """
    Render a template from the supplied string, with optional context data.

    This differs from Django's normal template system in that autoescaping
    is disabled by default. This is simply to make the tests below easier
    to read and write. You can re-enable the default behavior by passing True
    as the value of the autoescape parameter
    """
    context = Context(dictionary, autoescape=autoescape)
    return Template(template_string).render(context)

def test_convert_argument_value_to_boolean():
    assert convert_to_boolean(True) is True
Exemplo n.º 54
0
def set_dynamic_settings(s):
    """
    Called at the end of the project's settings module, and is passed
    its globals dict for updating with some final tweaks for settings
    that generally aren't specified, but can be given some better
    defaults based on other settings that have been specified. Broken
    out into its own function so that the code need not be replicated
    in the settings modules of other project-based apps that leverage
    Mezzanine's settings module.
    """

    # Moves an existing list setting value to a different position.
    move = lambda n, k, i: s[n].insert(i, s[n].pop(s[n].index(k)))
    # Add a value to the end of a list setting if not in the list.
    append = lambda n, k: s[n].append(k) if k not in s[n] else None
    # Add a value to the start of a list setting if not in the list.
    prepend = lambda n, k: s[n].insert(0, k) if k not in s[n] else None

    s["TEMPLATE_DEBUG"] = s.get("TEMPLATE_DEBUG", s.get("DEBUG", False))
    add_to_builtins("mezzanine.template.loader_tags")
    # Define some settings based on management command being run.
    management_command = sys.argv[1] if len(sys.argv) > 1 else ""
    # Some kind of testing is running via test or testserver.
    s["TESTING"] = management_command.startswith("test")
    # Some kind of development server is running via runserver or
    # runserver_plus
    s["DEV_SERVER"] = management_command.startswith("runserver")
    # Change tuple settings to lists for easier manipulation.
    s["INSTALLED_APPS"] = list(s["INSTALLED_APPS"])
    s["MIDDLEWARE_CLASSES"] = list(s["MIDDLEWARE_CLASSES"])
    s["STATICFILES_FINDERS"] = list(s.get("STATICFILES_FINDERS",
                                    STATICFILES_FINDERS))

    if s["DEV_SERVER"]:
        s["STATICFILES_DIRS"] = list(s.get("STATICFILES_DIRS", []))
        s["STATICFILES_DIRS"].append(s.pop("STATIC_ROOT"))

    # Set up cookie messaging if none defined.
    storage = "django.contrib.messages.storage.cookie.CookieStorage"
    s.setdefault("MESSAGE_STORAGE", storage)

    if s["TESTING"]:
        # Enable accounts when testing so the URLs exist.
        append("INSTALLED_APPS", "mezzanine.accounts")
    else:
        # Setup for optional apps.
        optional = list(s.get("OPTIONAL_APPS", []))
        if s.get("USE_SOUTH"):
            optional.append("south")
        elif not s.get("USE_SOUTH", True) and "south" in s["INSTALLED_APPS"]:
            s["INSTALLED_APPS"].remove("south")
        for app in optional:
            if app not in s["INSTALLED_APPS"]:
                try:
                    __import__(app)
                except ImportError:
                    pass
                else:
                    s["INSTALLED_APPS"].append(app)
    if "debug_toolbar" in s["INSTALLED_APPS"]:
        debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
        prepend("MIDDLEWARE_CLASSES", debug_mw)
    if "compressor" in s["INSTALLED_APPS"]:
        append("STATICFILES_FINDERS", "compressor.finders.CompressorFinder")

    # Ensure the Mezzanine auth backend is enabled if
    # mezzanine.accounts is being used.
    if "mezzanine.accounts" in s["INSTALLED_APPS"]:
        auth_backend = "mezzanine.core.auth_backends.MezzanineBackend"
        s.setdefault("AUTHENTICATION_BACKENDS", [])
        prepend("AUTHENTICATION_BACKENDS", auth_backend)

    # Ensure Grappelli is after Mezzanine in app order so that
    # admin templates are loaded in the correct order.
    grappelli_name = s.get("PACKAGE_NAME_GRAPPELLI")
    try:
        move("INSTALLED_APPS", grappelli_name, len(s["INSTALLED_APPS"]))
    except ValueError:
        s["GRAPPELLI_INSTALLED"] = False
        s["ADMIN_MEDIA_PREFIX"] = s["STATIC_URL"] + "admin/"
    else:
        s["GRAPPELLI_INSTALLED"] = True
        s.setdefault("GRAPPELLI_ADMIN_HEADLINE", "Mezzanine")
        s.setdefault("GRAPPELLI_ADMIN_TITLE", "Mezzanine")

    # Ensure admin is last in the app order so that admin templates
    # are loaded in the correct order.
    move("INSTALLED_APPS", "django.contrib.admin", len(s["INSTALLED_APPS"]))

    # Add missing apps if existing apps depend on them.
    if "mezzanine.blog" in s["INSTALLED_APPS"]:
        append("INSTALLED_APPS", "mezzanine.generic")
    if "mezzanine.generic" in s["INSTALLED_APPS"]:
        s.setdefault("COMMENTS_APP", "mezzanine.generic")
        append("INSTALLED_APPS", "django.contrib.comments")

    # Ensure mezzanine.boot is first.
    try:
        move("INSTALLED_APPS", "mezzanine.boot", 0)
    except ValueError:
        pass

    # Remove caching middleware if no backend defined.
    if not (s.get("CACHE_BACKEND") or s.get("CACHES")):
        s["MIDDLEWARE_CLASSES"] = [mw for mw in s["MIDDLEWARE_CLASSES"] if not
                                   (mw.endswith("UpdateCacheMiddleware") or
                                    mw.endswith("FetchFromCacheMiddleware"))]

    # Some settings tweaks for different DB engines.
    for (key, db) in s["DATABASES"].items():
        shortname = db["ENGINE"].split(".")[-1]
        if shortname == "sqlite3" and os.sep not in db["NAME"]:
            # If the Sqlite DB name doesn't contain a path, assume
            # it's in the project directory and add the path to it.
            db_path = os.path.join(s.get("PROJECT_ROOT", ""), db["NAME"])
            s["DATABASES"][key]["NAME"] = db_path
        elif shortname == "mysql":
            # Required MySQL collation for tests.
            s["DATABASES"][key]["TEST_COLLATION"] = "utf8_general_ci"
Exemplo n.º 55
0
from django.template.loader import add_to_builtins

# Need to add any tags that are used within the "nocache" tag, since otherwise
# django-adv-cache-tag doesn't know to load them.
#
add_to_builtins('django.templatetags.i18n')
Exemplo n.º 56
0
    INSTALLED_APPS=["djangothis"],
    TEMPLATE_CONTEXT_PROCESSORS=[
        "django.core.context_processors.request",
        "django.contrib.auth.context_processors.auth",
        "djangothis.app.context",
    ],
)

defaults.update(read_yaml_file(dotslash("config.yaml")))

d(**defaults)

from django.template.loader import add_to_builtins
from django.core.management import get_commands

add_to_builtins("djangothis.templatetags.raw")

def context(request):
    return {
        "settings": d.settings
    }

try:
    import views
except ImportError:
    pass
else:
    views

try:
    import forms
Exemplo n.º 57
0
import re
from django.conf.urls.defaults import url, patterns, include
from django.conf import settings
from django.contrib import admin
from django.template.loader import add_to_builtins

add_to_builtins('bootstrapform.templatetags.bootstrap')
add_to_builtins('django.contrib.humanize.templatetags.humanize')
add_to_builtins('avocado.templatetags.avocado_tags')
add_to_builtins('widget_tweaks.templatetags.widget_tweaks')

admin.autodiscover()

urlpatterns = patterns(
    '',
    # Landing page
    url(r'^$', 'varify.views.index', name='index'),

    # News
    url(r'^news/$', 'varify.views.news', name='news'),

    # Includes registration, moderation and authentication
    url(r'', include('varify.accounts.urls')),
    url(r'^', include('varify.samples.urls')),
    url(r'^sources/', include('varify.raw.sources.urls')),
    url(r'^genes/', include('varify.genes.urls')),

    # Cilantro
    url(r'^workspace/$', 'varify.views.app', name='cilantro'),
    url(r'^workspace/(?P<project>.+)/(?P<batch>.+)/(?P<sample>.+)/$',
        'varify.views.app',
Exemplo n.º 58
0
def get_version():
    return ".".join(map(str, VERSION))


__version__ = get_version()

git_version = None

if git_version is None:
    root_dir = os.path.abspath(
        os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
    if os.path.isdir(os.path.join(root_dir, '.git')):
        rev = subprocess.Popen(['git rev-parse --short HEAD'],
                               shell=True,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               cwd=root_dir).communicate()[0].strip()
        git_version = 'v{0}-{1}'.format(__version__, rev)
    else:
        git_version = __version__

try:
    # don't break setup.py if django hasn't been installed yet
    from django.template.loader import add_to_builtins
    add_to_builtins('django.templatetags.i18n')
    add_to_builtins('django.templatetags.future')
    add_to_builtins('django.templatetags.tz')
except ImportError:
    pass