Beispiel #1
0
    def test_url_tag_override(self):
        # we should be setting HOST_OVERRIDE_URL_TAG to True
        # but that doesn't really work since that setting is read only
        # on setup time so we have to fake it by manually setting the stage.
        try:
            from django.template.base import add_to_builtins
        except ImportError:  # Django 1.9+
            add_to_builtins = None

        if add_to_builtins:
            add_to_builtins('django_hosts.templatetags.hosts_override')

            self.assertRender("{% url 'simple-direct' host 'www' %}",
                          '//www.example.com/simple/')
            self.assertRender("{% url 'simple-direct' host 'www' as "
                              "simple_direct_url %}{{ simple_direct_url }}",
                              '//www.example.com/simple/')
        else:
            with self.settings(
                TEMPLATES=[{
                    'BACKEND': 'django.template.backends.django.DjangoTemplates',
                    'OPTIONS': {
                        'builtins': [
                            'django_hosts.templatetags.hosts_override',
                        ],
                    },
                }]
            ):
                self.assertRender("{% url 'simple-direct' host 'www' %}",
                                  '//www.example.com/simple/')
                self.assertRender("{% url 'simple-direct' host 'www' as "
                                  "simple_direct_url %}{{ simple_direct_url }}",
                                  '//www.example.com/simple/')
Beispiel #2
0
 def setUpClass(cls):
     super(TagParserTests, cls).setUpClass()
     if add_to_builtins is not None:
         # Django 1.8 and below.
         # Make it easier to run tests without needing to change INSTALLED_APPS
         add_to_builtins(
             "tag_parser.tests.templatetags.tag_parser_test_tags")
Beispiel #3
0
    def test_url_tag_override(self):
        # we should be setting HOST_OVERRIDE_URL_TAG to True
        # but that doesn't really work since that setting is read only
        # on setup time so we have to fake it by manually setting the stage.
        try:
            from django.template.base import add_to_builtins
        except ImportError:  # Django 1.9+
            add_to_builtins = None

        if add_to_builtins:
            add_to_builtins('django_hosts.templatetags.hosts_override')

            self.assertRender("{% url 'simple-direct' host 'www' %}",
                              '//www.example.com/simple/')
            self.assertRender(
                "{% url 'simple-direct' host 'www' as "
                "simple_direct_url %}{{ simple_direct_url }}",
                '//www.example.com/simple/')
        else:
            with self.settings(TEMPLATES=[{
                    'BACKEND':
                    'django.template.backends.django.DjangoTemplates',
                    'OPTIONS': {
                        'builtins': [
                            'django_hosts.templatetags.hosts_override',
                        ],
                    },
            }]):
                self.assertRender("{% url 'simple-direct' host 'www' %}",
                                  '//www.example.com/simple/')
                self.assertRender(
                    "{% url 'simple-direct' host 'www' as "
                    "simple_direct_url %}{{ simple_direct_url }}",
                    '//www.example.com/simple/')
Beispiel #4
0
def add_to_builtins_compat(name):
    if django.VERSION < (1, 9):
        from django.template.base import add_to_builtins
        add_to_builtins(name)
    else:
        from django.template import engines
        engines['django'].engine.builtins.append(name)
Beispiel #5
0
def add_to_builtins_compat(name):
    if django.VERSION < (1, 9):
        from django.template.base import add_to_builtins
        add_to_builtins(name)
    else:
        from django.template import engines
        engines['django'].engine.builtins.append(name)
Beispiel #6
0
    def ready(self):
        register()(check_template_settings)

        if DJANGO_VERSION < (1, 9):
            # add_to_builtins was removed in 1.9 and replaced with a
            # documented public API configured by the TEMPLATES setting.
            from django.template.base import add_to_builtins
            add_to_builtins("mezzanine.template.loader_tags")
Beispiel #7
0
    def handle(self, *args, **options):
        from django.conf import settings
        style = color_style()
        template_dirs = set(settings.TEMPLATE_DIRS)
        template_dirs |= set(options.get('includes', []))
        template_dirs |= set(
            getattr(settings, 'VALIDATE_TEMPLATES_EXTRA_TEMPLATE_DIRS', []))

        # Load in Templates from 1.8
        if hasattr(settings, 'TEMPLATES'):
            for template_engine in settings.TEMPLATES:
                if 'DIRS' in template_engine:
                    template_dirs |= set(template_engine['DIRS'])

        settings.TEMPLATE_DIRS = list(template_dirs)
        settings.TEMPLATE_DEBUG = True
        verbosity = int(options.get('verbosity', 1))
        errors = 0

        # Replace built in template tags with our own validating versions
        if options.get('check_urls', False):
            add_to_builtins('django_extensions.utils.validatingtemplatetags')

        for template_dir in template_dirs:
            for root, dirs, filenames in os.walk(template_dir):
                for filename in filenames:
                    if filename.endswith(".swp"):
                        continue
                    if filename.endswith("~"):
                        continue
                    filepath = os.path.join(root, filename)
                    if verbosity > 1:
                        print(filepath)
                    validatingtemplatetags.before_new_template(
                        options.get('force_new_urls', False))
                    try:
                        get_template(filename, [root])
                    except Exception as e:
                        errors += 1
                        print("%s: %s" %
                              (filepath,
                               style.ERROR("%s %s" %
                                           (e.__class__.__name__, str(e)))))
                    template_errors = validatingtemplatetags.get_template_errors(
                    )
                    for origin, line, message in template_errors:
                        errors += 1
                        print("%s(%s): %s" %
                              (origin, line, style.ERROR(message)))
                    if errors and options.get('break', False):
                        raise CommandError("Errors found")

        if errors:
            raise CommandError("%s errors found" % errors)
        print("%s errors found" % errors)
Beispiel #8
0
 def ready(self):
     super(YepesConfig, self).ready()
     from django import VERSION as DJANGO_VERSION
     if DJANGO_VERSION < (1, 9):
         from django.template.base import add_to_builtins
         add_to_builtins('yepes.defaultfilters')
         add_to_builtins('yepes.defaulttags')
     else:
         from django.template.engine import Engine
         Engine.default_builtins.append('yepes.defaultfilters')
         Engine.default_builtins.append('yepes.defaulttags')
    def handle(self, *args, **options):
        from django.conf import settings
        style = color_style()
        template_dirs = set(settings.TEMPLATE_DIRS)
        template_dirs |= set(options.get('includes', []))
        template_dirs |= set(
            getattr(
                settings,
                'VALIDATE_TEMPLATES_EXTRA_TEMPLATE_DIRS',
                []))
        settings.TEMPLATE_DIRS = list(template_dirs)
        settings.TEMPLATE_DEBUG = True
        verbosity = int(options.get('verbosity', 1))
        errors = 0

        template_loader = Loader()

        # Replace built in template tags with our own validating versions
        if options.get('check_urls', False):
            add_to_builtins('django_extensions.utils.validatingtemplatetags')

        for template_dir in template_dirs:
            for root, dirs, filenames in os.walk(template_dir):
                for filename in filenames:
                    if filename.endswith(".swp"):
                        continue
                    if filename.endswith("~"):
                        continue
                    filepath = os.path.join(root, filename)
                    if verbosity > 1:
                        print(filepath)
                    validatingtemplatetags.before_new_template(
                        options.get('force_new_urls', False))
                    try:
                        template_loader.load_template(filename, [root])
                    except Exception as e:
                        errors += 1
                        print(
                            "%s: %s" %
                            (filepath, style.ERROR(
                                "%s %s" %
                                (e.__class__.__name__, str(e)))))
                    template_errors = validatingtemplatetags.get_template_errors()
                    for origin, line, message in template_errors:
                        errors += 1
                        print(
                            "%s(%s): %s" %
                            (origin, line, style.ERROR(message)))
                    if errors and options.get('break', False):
                        raise CommandError("Errors found")

        if errors:
            raise CommandError("%s errors found" % errors)
        print("%s errors found" % errors)
Beispiel #10
0
    def ready(self):
        checks.register(check_root_hostconf)
        checks.register(check_default_host)

        if getattr(settings, 'HOST_OVERRIDE_URL_TAG', False):
            if add_to_builtins:
                add_to_builtins('django_hosts.templatetags.hosts_override')
            else:
                raise ImproperlyConfigured(
                    "On Django 1.9+, you must add "
                    "'django_hosts.templatetags.hosts_override' to the "
                    "TEMPLATES['OPTIONS']['builtins'] list instead of using "
                    "the HOST_OVERRIDE_URL_TAG setting.")
Beispiel #11
0
    def ready(self):
        checks.register(check_root_hostconf)
        checks.register(check_default_host)

        if getattr(settings, 'HOST_OVERRIDE_URL_TAG', False):
            if add_to_builtins:
                add_to_builtins('django_hosts.templatetags.hosts_override')
            else:
                raise ImproperlyConfigured(
                    "On Django 1.9+, you must add "
                    "'django_hosts.templatetags.hosts_override' to the "
                    "TEMPLATES['OPTIONS']['builtins'] list instead of using "
                    "the HOST_OVERRIDE_URL_TAG setting."
                )
Beispiel #12
0
def preload_templatetags():

    from django.conf import settings

    #from django.template.loader import add_to_builtins

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

    try:
        for lib in settings.TEMPLATE_TAGS:
            add_to_builtins(lib)
    except AttributeError:
        pass
    def test_url_tag_override(self):
        # we should be setting HOST_OVERRIDE_URL_TAG to True
        # but that doesn't really work since that setting is read only
        # on import time for Django < 1.7 and on setup time for >= 1.7
        # so we have to fake it by manually setting the stage
        try:
            from django.template.base import add_to_builtins
        except ImportError:  # Django < 1.8
            from django.template import add_to_builtins
        add_to_builtins("django_hosts.templatetags.hosts_override")

        self.assertRender("{% url 'simple-direct' host 'www' %}", "//www.example.com/simple/")
        self.assertRender(
            "{% url 'simple-direct' host 'www' as " "simple_direct_url %}{{ simple_direct_url }}",
            "//www.example.com/simple/",
        )
    def test_url_tag_override(self):
        # we should be setting HOST_OVERRIDE_URL_TAG to True
        # but that doesn't really work since that setting is read only
        # on import time for Django < 1.7 and on setup time for >= 1.7
        # so we have to fake it by manually setting the stage
        try:
            from django.template.base import add_to_builtins
        except ImportError:  # Django < 1.8
            from django.template import add_to_builtins
        add_to_builtins('django_hosts.templatetags.hosts_override')

        self.assertRender("{% url 'simple-direct' host 'www' %}",
                          '//www.example.com/simple/')
        self.assertRender("{% url 'simple-direct' host 'www' as "
                          "simple_direct_url %}{{ simple_direct_url }}",
                          '//www.example.com/simple/')
    def test_include_chart_jscss_tag_custom_dirs(self):
        add_to_builtins('django_nvd3.templatetags.nvd3_tags')

        rendered = self.render_template(
            "{% include_chart_jscss css_dir='css' js_dir='js' %}")

        # Not only does this test the output of the template tag,
        # but also the order of including the static files - mainly
        # d3 and nvd3 js files which should be in that order.
        expected = ('<link media="all" href="/static/css/nv.d3.min.css" '
                    'type="text/css" rel="stylesheet" />\n'
                    '<script src="/static/js/d3.min.js" '
                    'type="text/javascript" charset="utf-8"></script>\n'
                    '<script src="/static/js/nv.d3.min.js" '
                    'type="text/javascript" charset="utf-8"></script>\n\n')
        self.assertEqual(rendered, expected)
    def test_include_chart_jscss_tag_custom_dirs(self):
        add_to_builtins('django_nvd3.templatetags.nvd3_tags')

        rendered = self.render_template(
            "{% include_chart_jscss css_dir='css' js_dir='js' %}"
        )

        # Not only does this test the output of the template tag,
        # but also the order of including the static files - mainly
        # d3 and nvd3 js files which should be in that order.
        expected = (
            '<link media="all" href="/static/css/nv.d3.min.css" '
            'type="text/css" rel="stylesheet" />\n'
            '<script src="/static/js/d3.min.js" '
            'type="text/javascript" charset="utf-8"></script>\n'
            '<script src="/static/js/nv.d3.min.js" '
            'type="text/javascript" charset="utf-8"></script>\n\n'
        )
        self.assertEqual(rendered, expected)
Beispiel #17
0
def define_table(columns):
    from django.template.base import add_to_builtins
    add_to_builtins('silo.templatetags.underscoretags')
    
    """
    Dynamically builds a django-tables2 table without specifying the column names
    It is important to build the django-tables2 dynamically because each time a silo 
    is loaded from MongoDB, it is not known what columns heading it has or how mnay columns it has
    """
    EDIT_DEL_TEMPLATE = '''
        <a class="btn btn-default btn-xs" role="button" href="/value_edit/{{ record|get:'_id'|get:'$oid' }}">Edit</a>
        <a class="btn btn-danger btn-xs btn-del" style="color: #FFF;" role="button" href="/value_delete/{{ record|get:'_id'|get:'$oid'  }}" title="Are you sure you want to delete this record?">Delete</a> 
        '''
    #add the operations to the table first then append the dynamic table columns
    attrs = {}
    attrs['Operation'] = tables.TemplateColumn(EDIT_DEL_TEMPLATE)
    attrs.update(dict((c, tables.Column()) for c in columns))
    attrs['Meta'] = type('Meta', (), dict(exclude=["_id", "edit_date", "create_date"], attrs={"class":"paleblue", "orderable":"True", "width":"100%"}) )
    
    klass = type('DynamicTable', (tables.Table,), attrs)
    return klass
Beispiel #18
0
def init():
    # Our eventual aim is to patch the render() method on the Node objects
    # corresponding to custom template tags. However we have to jump through
    # a number of hoops in order to get access to the object.
    #
    # 1. Add ourselves to the set of built in template tags
    #    This allows us to replace the 'load' template tag which controls
    #    the loading of custom template tags
    # 2. Delegate to default load with replaced parser
    #    We provide our own parser class so we can catch and intercept
    #    calls to add_library.
    # 3. add_library receives a library of template tags
    #    It iterates through each template tag, wrapping its compile function
    # 4. compile is called as part of compiling the template
    #    Our wrapper is called instead of the original templatetag compile
    #    function. We delegate to the original function, but then modify
    #    the resulting object by wrapping its render() function. This
    #    render() function is what ends up being timed and appearing in the
    #    tree.
    add_to_builtins('speedbar.modules.templates')

    @trace_method(Template)
    def __init__(self, *args, **kwargs):
        name = args[2] if len(args) >= 3 else '<Unknown Template>'
        return ('TEMPLATE_COMPILE', 'Compile template: ' + name, {})

    @trace_method(Template)
    def render(self, *args, **kwargs):
        name = self.name if self.name is not None else '<Unknown Template>'
        return ('TEMPLATE_RENDER', 'Render template: ' + name, {})

    @trace_method(BlockNode)
    def render(self, *args, **kwargs):
        return ('BLOCK_RENDER', 'Render block: ' + self.name, {})

    @trace_method(TemplateResponse)
    def resolve_context(self, *args, **kwargs):
        return ('TEMPLATE_CONTEXT', 'Resolve context', {})
Beispiel #19
0
    def configure(self, settings_module=None, overrides=None):
        """
        """
        if self._wrapped is not empty:
            raise RuntimeError('Settings already configured.')

        from django.conf import ENVIRONMENT_VARIABLE, settings as django_settings
        from django import setup
        from django.template.base import add_to_builtins

        if not django_settings.configured:
            settings_module = settings_module or 'instance.defaults'
            os.environ.setdefault(ENVIRONMENT_VARIABLE, settings_module)
            setup()
        add_to_builtins("instance.templatetags.loader_tags")

        env = django_settings._wrapped.__dict__
        if overrides:
            env.update(overrides)
        self._configure_data_root(env)
        self._configure_database(env)
        self._configure_defaults(env)
        self._wrapped = Environment(env) #shallow copy
        self._site_cache = {}
Beispiel #20
0
 def ready(self):
     # The following enables legacy ARCUtils behavior by adding a
     # bunch of default template tags. It would be better to add the
     # relevant {% load xxx %} in the templates that use these tags.
     # Django 1.9 has a new setting that "officially" enables adding
     # default tags, so we could leave this until we upgrade to 1.9.
     from django.template.base import add_to_builtins
     add_to_builtins('django.contrib.staticfiles.templatetags.staticfiles')
     add_to_builtins('bootstrapform.templatetags.bootstrap')
     add_to_builtins('arcutils.templatetags.arc')
Beispiel #21
0
    def ready(self):
        """
        Do a bunch of monkey patching based on the ARCUTILS_FEATURES setting
        """
        from django.conf import settings
        ARCUTILS_FEATURES = getattr(settings, 'ARCUTILS_FEATURES', DEFAULT_FEATURES)

        # monkey patch the PasswordResetForm so it indicates if a user does not exist
        if ARCUTILS_FEATURES.get('warn_on_invalid_email_during_password_reset'):
            from django.contrib.auth.forms import PasswordResetForm

            original_clean_email = getattr(PasswordResetForm, "clean_email", lambda self: self.cleaned_data['email'])
            def _clean_email(self):
                from django.contrib.auth import get_user_model
                email = self.cleaned_data['email']
                UserModel = get_user_model()
                if not UserModel.objects.filter(email=email, is_active=True).exists():
                    raise forms.ValidationError("A user with that email address does not exist!")

                return original_clean_email(self)

            PasswordResetForm.clean_email = _clean_email

        # hook up the session clearer
        CLEAR_EXPIRED_SESSIONS_AFTER_N_REQUESTS = getattr(settings, 'CLEAR_EXPIRED_SESSIONS_AFTER_N_REQUESTS', 100)
        CLEAR_EXPIRED_SESSIONS_ENABLED = is_installed('django.contrib.sessions') and CLEAR_EXPIRED_SESSIONS_AFTER_N_REQUESTS is not None
        if ARCUTILS_FEATURES.get('clear_expired_sessions') and CLEAR_EXPIRED_SESSIONS_ENABLED:
            from .sessions import patch_sessions

            patch_sessions(CLEAR_EXPIRED_SESSIONS_AFTER_N_REQUESTS)

        # add all the templatetag libraries we want available by default
        if ARCUTILS_FEATURES.get('templatetags'):
            from django.template.base import add_to_builtins

            add_to_builtins('django.contrib.staticfiles.templatetags.staticfiles')
            # add the arc template tags to the builtin tags, and the bootstrap tag
            add_to_builtins('arcutils.templatetags.arc')
            add_to_builtins('arcutils.templatetags.bootstrap')

        # make the `required_css_class` attribute for forms and fields
        # "required" by default
        if ARCUTILS_FEATURES.get('add_css_classes_to_forms'):
            from django.forms.fields import Field
            from django import forms

            forms.Form.required_css_class = "required"
            forms.ModelForm.required_css_class = "required"
            Field.required_css_class = "required"
Beispiel #22
0
    def send_mail(self, lang, subject, text, recipient):
        """
        This method will send an email to given recipient with attached cv pdf

        :param lang: The language of sending CV
        :type lang: str
        :param subject: The subject of sending email
        :type subject: str
        :param text: The body of sending email
        :type text: str
        :param recipient: The target email
        :type recipient: str
        """
        pdf = self.translations.filter(language_code=lang).first().pdf
        pdf_content = urllib2.urlopen('http://buildcv.org' + pdf).read()
        pdf_name = '%s_%s_CV_%s-%s.pdf' % (
            self.human.nume(), self.human.prenume(), self.title, lang)
        message = EmailMessage(subject,
                               text,
                               '*****@*****.**', [recipient], [],
                               reply_to=[self.human.email])
        message.attach(pdf_name, pdf_content, 'application/pdf')
        message.send()
        return {'success': True, 'message': 'The email was sent'}


admin.site.register(CV)

add_to_builtins('udata.templatetags.syns')
Beispiel #23
0
from django import http
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, get_list_or_404, render
from django.template.base import add_to_builtins

from .models import League, Game, RosterStats, Preference, PickerResultException
from . import utils
from . import forms
from .decorators import management_user_required


datetime_now = utils.datetime_now
add_to_builtins('picker.templatetags.picker_tags')


#-------------------------------------------------------------------------------
def picker_adapter(view):
    @functools.wraps(view)
    def view_wrapper(request, *args, **kws):
        league = League.get(kws.pop('league'))
        result = view(request, league, *args, **kws)
        if isinstance(result, http.HttpResponse):
            return result
        
        tmpl, ctx = (result, {}) if isinstance(result, basestring) else result
        tmpls = utils.get_templates(league, tmpl)
        data = {
            'league': league,
Beispiel #24
0
from __future__ import unicode_literals

try:
    # Django 1.6
    from django.template.base import add_to_builtins

    # This will add the localsite tags as built-in tags, and override the
    # existing {% url %} tag in Django.
    add_to_builtins(__name__ + '.localsite')
except ImportError:
    # This is instead handled in the TEMPLATES settings.
    pass
Beispiel #25
0
            if not code.buffer:
                codeTag = code.val.strip().split(' ', 1)[0]
                if codeTag in self.autocloseCode:
                    self.buf.append('{%% end%s %%}' % codeTag)

    def attributes(self, attrs):
        return "{%% __pypugjs_attrs %s %%}" % attrs


try:
    try:
        from django.template.base import add_to_builtins
    except ImportError:  # Django < 1.8
        from django.template import add_to_builtins
    add_to_builtins('pypugjs.ext.django.templatetags')
except ImportError:
    # Django 1.9 removed add_to_builtins and instead
    # provides a setting to specify builtins:
    # TEMPLATES['OPTIONS']['builtins'] = ['pypugjs.ext.django.templatetags']
    pass

try:
    from django.utils.encoding import force_text as to_text
except ImportError:
    from django.utils.encoding import force_unicode as to_text


def decorate_templatize(func):
    def templatize(src, origin=None):
        src = to_text(src, settings.FILE_CHARSET)
Beispiel #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.
    """

    # 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", []):
        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()

    if s.get("TIME_ZONE", None) is None:
        tz = get_best_local_timezone()
        s["TIME_ZONE"] = tz
        warn("TIME_ZONE setting is not set, using closest match: %s" % tz)

    # 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",
                           "LANGUAGES"]
    for setting in tuple_list_settings[:]:
        if not isinstance(s.get(setting, []), list):
            s[setting] = list(s[setting])
        else:
            # Setting is already a list, so we'll exclude it from
            # the list of settings we'll revert back to tuples.
            tuple_list_settings.remove(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"
        append("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

    # 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"]))

    # Ensure we have a test runner (removed in Django 1.6)
    s.setdefault("TEST_RUNNER", "django.test.simple.DjangoTestSuiteRunner")

    # 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"))]

    # If only LANGUAGE_CODE has been defined, ensure the other required
    # settings for translations are configured.
    if (s.get("LANGUAGE_CODE") and len(s.get("LANGUAGES", [])) == 1 and
            s["LANGUAGE_CODE"] != s["LANGUAGES"][0][0]):
        s["USE_I18N"] = True
        s["LANGUAGES"] = [(s["LANGUAGE_CODE"], "")]

    # 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"
Beispiel #27
0
import django
from django.conf import settings
from django.core import urlresolvers
from django.template import base

# To load docutils extensions somewhere
from missing import admindocs

if django.VERSION < (1, 9):
    # To be able to force use of "contextblock" tag immediately after "extends" tag, we add it to built-in tags
    base.add_to_builtins('missing.templatetags.context_tags')

# NoReverseMatch exceptions are silent (replaced by TEMPLATE_STRING_IF_INVALID setting), but we
# disable this behavior here
if getattr(settings, 'TEMPLATE_URL_RESOLVERS_DEBUG', False) and getattr(settings, 'TEMPLATE_DEBUG', False):
    urlresolvers.NoReverseMatch.silent_variable_failure = False
Beispiel #28
0
from django.template.base import add_to_builtins

add_to_builtins('support.templatetags.support_tags')
add_to_builtins('support.templatetags.form_tags')
Beispiel #29
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 
# 
# 
# Copyright (c) 2008-2011 University of Dundee.
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
# Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2012.
# 

from django.template.base import add_to_builtins

add_to_builtins('omeroweb.webgateway.templatetags.defaulttags')
Beispiel #30
0
    def child_behavior(self):
        if self.child_listings is None:
            return ListingHandler.ALL if self._instance.tree_parent_id else ListingHandler.NONE
        return self.child_listings

app_registry.register('ella', EllaAppDataContainer, Category)


# connect redis listing handler signals
connect_signals()

# connect cache invalidation signals
connect_invalidation_signals()

try:
    # django < 1.9
    from django.template.base import add_to_builtins
except ImportError:
    pass
else:
    # add core templatetags to builtin so that you don't have to invoke {% load core %} in every template
    add_to_builtins('ella.core.templatetags.core')
    # keep this here for backwards compatibility
    add_to_builtins('ella.core.templatetags.related')
    # and custom urls
    add_to_builtins('ella.core.templatetags.custom_urls_tags')
    # and the same for i18n
    add_to_builtins('django.templatetags.i18n')
    # and photos are always useful
    add_to_builtins('ella.photos.templatetags.photos')
Beispiel #31
0
# License along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from django.core.signals import request_finished
from django.db.models import signals, get_models
from django.db import DEFAULT_DB_ALIAS
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.template.base import add_to_builtins

from freppledb.common import models as common_models
from freppledb.common.middleware import resetRequest

# Make our tags built-in, so we don't have to load them any more in our
# templates with a 'load' tag.
add_to_builtins('freppledb.common.templatetags.base_utils')


def removeModelPermissions(app, model, db=DEFAULT_DB_ALIAS):
    Permission.objects.all().using(db).filter(
        content_type__app_label=app, content_type__model=model).delete()


def createViewPermissions(app,
                          created_models,
                          verbosity,
                          db=DEFAULT_DB_ALIAS,
                          **kwargs):
    if db != DEFAULT_DB_ALIAS:
        return
    # Create model read permissions
Beispiel #32
0
from django.template.base import add_to_builtins


add_to_builtins('commenting.templatetags.ajax')
add_to_builtins('commenting.templatetags.custom_tags')
Beispiel #33
0
ROOT_URLCONF = 'tests.urls'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3')
    }
}

# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = False

# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'

TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'tests/templates'), )

# shortcut for in form templates
from django.template.base import add_to_builtins
add_to_builtins('viewform.templatetags.viewform')

try:
    from deploy.local_settings import *  # NOQA
except ImportError:
    pass
# following PEP 440
__version__ = "1.7.3"

VERSION = (1, 7, 3)

import django
if django.VERSION < (1, 9):
    # Make sure the ``{% print %}`` is always available, even without a {% load debugtools_tags %} call.
    # This feature is no longer available in Django 1.9, which adds an explicit configuration for it:
    # see: https://docs.djangoproject.com/en/1.9/releases/1.9/#django-template-base-add-to-builtins-is-removed
    #
    # This function is used here 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.base import add_to_builtins
    add_to_builtins("debugtools.templatetags.debugtools_tags")
Beispiel #35
0
d(**defaults)

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

from django.core.management import get_commands

try:
    import importlib
except ImportError:
    from django.utils import importlib

add_to_builtins("djangothis.templatetags.raw")


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

try:
    import views
except ImportError:
    pass
else:
    views

try:
Beispiel #36
0
    """
    dictionary = dictionary or {}
    if isinstance(template_name, (list, tuple)):
        t = select_template(template_name)
    else:
        t = get_template(template_name)
    if not context_instance:
        return t.render(Context(dictionary))
    # Add the dictionary to the context stack, ensuring it gets removed again
    # to keep the context_instance in the same state it started in.
    context_instance.update(dictionary)
    try:
        return t.render(context_instance)
    finally:
        context_instance.pop()

def select_template(template_name_list):
    "Given a list of template names, returns the first that can be loaded."
    not_found = []
    for template_name in template_name_list:
        try:
            return get_template(template_name)
        except TemplateDoesNotExist, e:
            if e.args[0] not in not_found:
                not_found.append(e.args[0])
            continue
    # If we get here, none of the templates could be loaded
    raise TemplateDoesNotExist(', '.join(not_found))

add_to_builtins('django.template.loader_tags')
Beispiel #37
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", []):
        warn("You haven't defined the ALLOWED_HOSTS settings, which "
             "Django requires. Will fall back to the domains "
             "configured as sites.")
        s["ALLOWED_HOSTS"] = SitesAllowedHosts()

    if s.get("TIME_ZONE", None) is None:
        tz = get_best_local_timezone()
        s["TIME_ZONE"] = tz
        warn("TIME_ZONE setting is not set, using closest match: %s" % tz)

    # 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", "LANGUAGES", "TEMPLATE_CONTEXT_PROCESSORS"
    ]
    for setting in tuple_list_settings[:]:
        if not isinstance(s.get(setting, []), list):
            s[setting] = list(s[setting])
        else:
            # Setting is already a list, so we'll exclude it from
            # the list of settings we'll revert back to tuples.
            tuple_list_settings.remove(setting)

    # From Mezzanine 3.1.2 and onward we added the context processor
    # for handling the page variable in templates - here we help
    # upgrading by adding it if missing, with a warning. This helper
    # can go away eventually.
    cp = "mezzanine.pages.context_processors.page"
    if ("mezzanine.pages" in s["INSTALLED_APPS"]
            and cp not in s["TEMPLATE_CONTEXT_PROCESSORS"]):
        warn("%s is required in the TEMPLATE_CONTEXT_PROCESSORS setting. "
             "Adding it now, but you should update settings.py to "
             "explicitly include it." % cp)
        append("TEMPLATE_CONTEXT_PROCESSORS", cp)

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

    # If required, add django-modeltranslation for both tests and deployment
    if not s.get("USE_MODELTRANSLATION", False):
        remove("INSTALLED_APPS", "modeltranslation")
    else:
        try:
            __import__("modeltranslation")
        except ImportError:
            # django-modeltranslation is not installed, remove setting so
            # admin won't try to import it
            s["USE_MODELTRANSLATION"] = False
            remove("INSTALLED_APPS", "modeltranslation")
            warn("USE_MODETRANSLATION setting is set to True but django-"
                 "modeltranslation is not installed. Disabling it.")
        else:
            # Force i18n so we are assured that modeltranslation is active
            s["USE_I18N"] = True
            append("INSTALLED_APPS", "modeltranslation")

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

    if s["TESTING"]:
        # Triggers interactive superuser creation and some pyc/pyo tests
        # fail with standard permissions.
        remove("INSTALLED_APPS", "django_extensions")

    if "debug_toolbar" in s["INSTALLED_APPS"]:
        debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
        append("MIDDLEWARE_CLASSES", debug_mw)
        # Ensure debug_toolbar is before modeltranslation to avoid
        # races for configuration.
        move("INSTALLED_APPS", "debug_toolbar", 0)

    # 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

    # Ensure admin is at the bottom of the app order so that admin
    # templates are loaded in the correct order, and that staticfiles
    # is also at the end so its runserver can be overridden.
    for app in ["django.contrib.admin", "django.contrib.staticfiles"]:
        try:
            move("INSTALLED_APPS", app, len(s["INSTALLED_APPS"]))
        except ValueError:
            pass

    # 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_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"))
        ]

    # If only LANGUAGE_CODE has been defined, ensure the other required
    # settings for translations are configured.
    if (s.get("LANGUAGE_CODE") and len(s.get("LANGUAGES", [])) == 1
            and s["LANGUAGE_CODE"] != s["LANGUAGES"][0][0]):
        s["USE_I18N"] = True
        s["LANGUAGES"] = [(s["LANGUAGE_CODE"], "")]

    # 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":
            # If the Sqlite DB name doesn't contain a path, assume
            # it's in the project directory and add the path to it.
            if "NAME" in db and os.sep not in db["NAME"]:
                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"
Beispiel #38
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", []):
        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()

    if s.get("TIME_ZONE", None) is None:
        tz = get_best_local_timezone()
        s["TIME_ZONE"] = tz
        warn("TIME_ZONE setting is not set, using closest match: %s" % tz)

    # 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",
                           "LANGUAGES", "TEMPLATE_CONTEXT_PROCESSORS"]
    for setting in tuple_list_settings[:]:
        if not isinstance(s.get(setting, []), list):
            s[setting] = list(s[setting])
        else:
            # Setting is already a list, so we'll exclude it from
            # the list of settings we'll revert back to tuples.
            tuple_list_settings.remove(setting)

    # From Mezzanine 3.1.2 and onward we added the context processor
    # for handling the page variable in templates - here we help
    # upgrading by adding it if missing, with a warning. This helper
    # can go away eventually.
    cp = "mezzanine.pages.context_processors.page"
    if ("mezzanine.pages" in s["INSTALLED_APPS"] and
            cp not in s["TEMPLATE_CONTEXT_PROCESSORS"]):
        warn("%s is required in the TEMPLATE_CONTEXT_PROCESSORS setting. "
             "Adding it now, but you should update settings.py to "
             "explicitly include it." % cp)
        append("TEMPLATE_CONTEXT_PROCESSORS", cp)

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

    # If required, add django-modeltranslation for both tests and deployment
    if not s.get("USE_MODELTRANSLATION", False):
        remove("INSTALLED_APPS", "modeltranslation")
    else:
        try:
            __import__("modeltranslation")
        except ImportError:
            pass
        else:
            # Force i18n so we are assured that modeltranslation is active
            s["USE_I18N"] = True
            append("INSTALLED_APPS", "modeltranslation")

    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"
        append("MIDDLEWARE_CLASSES", debug_mw)
        # Ensure debug_toolbar is before modeltranslation to avoid
        # races for configuration.
        move("INSTALLED_APPS", "debug_toolbar", 0)
    # 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")
    if s["TESTING"]:
        # Optional apps aren't installed when testing, but we need
        # grappelli to perform some admin tests for certain HTML.
        try:
            __import__(grappelli_name)
        except ImportError:
            pass
        else:
            append("INSTALLED_APPS", grappelli_name)
    try:
        move("INSTALLED_APPS", grappelli_name, len(s["INSTALLED_APPS"]))
    except ValueError:
        s["GRAPPELLI_INSTALLED"] = False
    else:
        s["GRAPPELLI_INSTALLED"] = True

    # 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"]))

    # Ensure we have a test runner (removed in Django 1.6)
    s.setdefault("TEST_RUNNER", "django.test.simple.DjangoTestSuiteRunner")

    # 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"))]

    # If only LANGUAGE_CODE has been defined, ensure the other required
    # settings for translations are configured.
    if (s.get("LANGUAGE_CODE") and len(s.get("LANGUAGES", [])) == 1 and
            s["LANGUAGE_CODE"] != s["LANGUAGES"][0][0]):
        s["USE_I18N"] = True
        s["LANGUAGES"] = [(s["LANGUAGE_CODE"], "")]

    # 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"
Beispiel #39
0
# following PEP 386
__version__ = "1.2.1"

VERSION = (1, 2, 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.base import add_to_builtins
add_to_builtins("debugtools.templatetags.debug_tags")
Beispiel #40
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", []):
        warn("You haven't defined the ALLOWED_HOSTS settings, which "
             "Django requires. Will fall back to the domains "
             "configured as sites.")
        s["ALLOWED_HOSTS"] = SitesAllowedHosts()

    if s.get("TIME_ZONE", None) is None:
        tz = get_best_local_timezone()
        s["TIME_ZONE"] = tz
        warn("TIME_ZONE setting is not set, using closest match: %s" % tz)

    # 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",
                           "LANGUAGES", "TEMPLATE_CONTEXT_PROCESSORS"]
    for setting in tuple_list_settings[:]:
        if not isinstance(s.get(setting, []), list):
            s[setting] = list(s[setting])
        else:
            # Setting is already a list, so we'll exclude it from
            # the list of settings we'll revert back to tuples.
            tuple_list_settings.remove(setting)

    # From Mezzanine 3.1.2 and onward we added the context processor
    # for handling the page variable in templates - here we help
    # upgrading by adding it if missing, with a warning. This helper
    # can go away eventually.
    cp = "mezzanine.pages.context_processors.page"
    if ("mezzanine.pages" in s["INSTALLED_APPS"] and
            cp not in s["TEMPLATE_CONTEXT_PROCESSORS"]):
        warn("%s is required in the TEMPLATE_CONTEXT_PROCESSORS setting. "
             "Adding it now, but you should update settings.py to "
             "explicitly include it." % cp)
        append("TEMPLATE_CONTEXT_PROCESSORS", cp)

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

    # If required, add django-modeltranslation for both tests and deployment
    if not s.get("USE_MODELTRANSLATION", False):
        remove("INSTALLED_APPS", "modeltranslation")
    else:
        try:
            __import__("modeltranslation")
        except ImportError:
            # django-modeltranslation is not installed, remove setting so
            # admin won't try to import it
            s["USE_MODELTRANSLATION"] = False
            remove("INSTALLED_APPS", "modeltranslation")
            warn("USE_MODETRANSLATION setting is set to True but django-"
                    "modeltranslation is not installed. Disabling it.")
        else:
            # Force i18n so we are assured that modeltranslation is active
            s["USE_I18N"] = True
            append("INSTALLED_APPS", "modeltranslation")
            # Ensure mezzanine.pages falls before any apps that subclass the
            # Page model, otherwise modeltranslation doesn't work.
            get_pos = lambda n, k: s[n].index(k) if k in s[n] else len(s[n])
            page_pos = get_pos("INSTALLED_APPS", "mezzanine.pages")
            subclass_pos = min([get_pos("INSTALLED_APPS", app) for app in
                ("mezzanine.forms", "mezzanine.gallery", "cartridge.shop")])
            if page_pos > subclass_pos:
                move("INSTALLED_APPS", "mezzanine.pages", subclass_pos)

    # Setup for optional apps.
    optional = list(s.get("OPTIONAL_APPS", []))
    if s.get("USE_SOUTH") and VERSION < (1, 7):
        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 s["TESTING"]:
        # Following bits are work-arounds for some assumptions that
        # Django 1.5's tests make.

        # Triggers interactive superuser creation and some pyc/pyo tests
        # fail with standard permissions.
        remove("INSTALLED_APPS", "django_extensions")

    # To support migrations for both Django 1.7 and South, South's old
    # migrations for each app were moved into "app.migrations.south"
    # packages. Here we assign each of these to SOUTH_MIGRATION_MODULES
    # allowing South to find them.
    if "south" in s["INSTALLED_APPS"]:
        s.setdefault("SOUTH_MIGRATION_MODULES", {})
        for app in s["INSTALLED_APPS"]:
            # We need to verify the path to the custom migrations
            # package exists for each app. We can't simply try
            # and import it, for some apps this causes side effects,
            # so we need to import something higher up to get at its
            # filesystem path - this can't be the actual app either,
            # side effects again, but we can generally import the
            # top-level package for apps that are contained within
            # one, which covers Mezzanine, Cartridge, Drum.
            if "." not in app:
                continue
            migrations = "%s.migrations.south" % app
            parts = migrations.split(".", 1)
            root = path_for_import(parts[0])
            other = parts[1].replace(".", os.sep)
            if os.path.exists(os.path.join(root, other)):
                s["SOUTH_MIGRATION_MODULES"][app.split(".")[-1]] = migrations

    if "debug_toolbar" in s["INSTALLED_APPS"]:
        debug_mw = "debug_toolbar.middleware.DebugToolbarMiddleware"
        append("MIDDLEWARE_CLASSES", debug_mw)
        # Ensure debug_toolbar is before modeltranslation to avoid
        # races for configuration.
        move("INSTALLED_APPS", "debug_toolbar", 0)

    # 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

    # Ensure admin is at the bottom of the app order so that admin
    # templates are loaded in the correct order, and that staticfiles
    # is also at the end so its runserver can be overridden.
    apps = ["django.contrib.admin"]
    if VERSION >= (1, 7):
        apps += ["django.contrib.staticfiles"]
    for app in apps:
        try:
            move("INSTALLED_APPS", app, len(s["INSTALLED_APPS"]))
        except ValueError:
            pass

    # 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_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"))]

    # If only LANGUAGE_CODE has been defined, ensure the other required
    # settings for translations are configured.
    if (s.get("LANGUAGE_CODE") and len(s.get("LANGUAGES", [])) == 1 and
            s["LANGUAGE_CODE"] != s["LANGUAGES"][0][0]):
        s["USE_I18N"] = True
        s["LANGUAGES"] = [(s["LANGUAGE_CODE"], "")]

    # 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":
            # If the Sqlite DB name doesn't contain a path, assume
            # it's in the project directory and add the path to it.
            if "NAME" in db and os.sep not in db["NAME"]:
                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"
Beispiel #41
0
limitations under the License"""
import django

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin


if django.VERSION < (1, 8): # add_to_builtins removed in Django 1.9
    try:
        from django.template.base import add_to_builtins
    except ImportError:  # Django < 1.7
        from django.template.loader import add_to_builtins

if django.VERSION < (1, 5) and django.VERSION > (1, 8):  # load the "future" {% url %} tag
    add_to_builtins('django.templatetags.future')

if django.VERSION < (1, 7):
    # Django doing autodiscover automatically:
    # https://docs.djangoproject.com/en/dev/releases/1.7/#app-loading-refactor
    admin.autodiscover()

graphite_urls = patterns(
    '',
    ('^admin/', include(admin.site.urls)),
    ('^render/?', include('graphite.render.urls')),
    ('^composer/?', include('graphite.composer.urls')),
    ('^metrics/?', include('graphite.metrics.urls')),
    ('^browser/?', include('graphite.browser.urls')),
    ('^account/', include('graphite.account.urls')),
    ('^dashboard/?', include('graphite.dashboard.urls')),
Beispiel #42
0
#                 UNIFI CONFIGURATION           #
#################################################
from unifi_settings import *
from unifi_secret import *

INSTALLED_APPS += UNIFI_INSTALLED_APPS

LOGIN_URL = UNIFI_LOGIN_URL
LOGIN_REDIRECT_URL = UNIFI_LOGIN_REDIRECT_URL

TEMPLATES[0]['OPTIONS'][
    'context_processors'] += UNIFI_TEMPLATE_CONTEXT_PROCESSORS

# shortcut for in form templates
try:
    # shortcut for in form templates
    from django.template.base import add_to_builtins
    add_to_builtins(UNIFI_TEMPLATE_BUILTINS)
except ImportError:
    """
    Django 1.9.
    """
    TEMPLATES[0]['OPTIONS']['builtins'] = [
        UNIFI_TEMPLATE_BUILTINS,
    ]

AUTHENTICATION_BACKENDS = UNIFI_AUTHENTICATION_BACKENDS
SOCIAL_AUTH_PIPELINE = UNIFI_SOCIAL_AUTH_PIPELINE
#When DEBUG = True Social Auth exception handling to redirected url is disabled
SOCIAL_AUTH_LOGIN_ERROR_URL = '/guest/s/default/'
Beispiel #43
0
 def ready(self):
     add_to_builtins('django.templatetags.i18n')
     add_to_builtins('django.templatetags.tz')
Beispiel #44
0
    for d in ('./', './template_set', './_layouts', './_includes'):
        dd = os.path.join(PROJECT_ROOT_PATH, d)
        if os.path.exists(dd):
            DIR_TEMPLATES.append(dd)

DIR_TEMPLATES.append(DEFAULT_TEMPLATES)

TEMPLATES = [
    { 'BACKEND': 'django.template.backends.django.DjangoTemplates',
      'DIRS': DIR_TEMPLATES,
  },
]

MIDDLEWARE_CLASSES = []

add_to_builtins('actionkit_templates.templatetags.actionkit_tags')

def _get_context_data(request, name, page, use_referer=False):
    from actionkit_templates.contexts.page_contexts import contexts
    port = '4000'
    hostport = request.get_host().split(':')
    if len(hostport) > 1:
        port = hostport[1]

    if use_referer:
        paths = urlparse.urlparse(request.META['HTTP_REFERER']).path.split('/')
        if paths and len(paths) > 1:
            name = paths[1]
            if len(paths) > 2:
                page = paths[2]
Beispiel #45
0
d(**defaults)

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

from django.core.management import get_commands

try:
    import importlib
except ImportError:
    from django.utils import importlib

add_to_builtins("djangothis.templatetags.raw")


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


try:
    import views
except ImportError:
    pass
else:
    views

try:
    import forms
Beispiel #46
0
default_app_config = 'material.frontend.apps.ModulesDiscoverConfig'


if getattr(settings, 'MATERIAL_FRONTEND_AUTOREGISTER', True):
    # Register middleware
    if 'material.frontend.middleware.SmoothNavigationMiddleware' not in settings.MIDDLEWARE_CLASSES:
        settings.MIDDLEWARE_CLASSES += ('material.frontend.middleware.SmoothNavigationMiddleware',)

    if 'material.frontend.middleware.UnpjaxMiddleware' not in settings.MIDDLEWARE_CLASSES:
        settings.MIDDLEWARE_CLASSES += ('material.frontend.middleware.UnpjaxMiddleware',)

    # Register pjax template tag
    try:
        from django.template.base import add_to_builtins
        add_to_builtins("material.frontend.templatetags.pjax_tags")
    except ImportError:
        """
        Django 1.9
        """
        for engine in settings.TEMPLATES:
            if engine['BACKEND'] == 'django.template.backends.django.DjangoTemplates':
                if 'OPTIONS' not in engine:
                    engine['OPTIONS'] = {}
                if 'builtins' not in engine['OPTIONS']:
                    engine['OPTIONS']['builtins'] = []
                if "material.frontend.templatetags.pjax_tags" not in engine['OPTIONS']['builtins']:
                    engine['OPTIONS']['builtins'].append("material.frontend.templatetags.pjax_tags")

    # Context processors
    for engine in settings.TEMPLATES:
Beispiel #47
0
from django.db import transaction
from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect
from django.template.base import add_to_builtins

from appliances.api import json_response
from appliances.models import (
    Provider, AppliancePool, Appliance, Group, Template, MismatchVersionMailer, User)
from appliances.tasks import (appliance_power_on, appliance_power_off, appliance_suspend,
    anyvm_power_on, anyvm_power_off, anyvm_suspend, anyvm_delete, delete_template_from_provider,
    appliance_rename, wait_appliance_ready, mark_appliance_ready, appliance_reboot)

from sprout.log import create_logger
from utils.providers import get_mgmt

add_to_builtins('appliances.templatetags.appliances_extras')


def go_home(request):
    return redirect(index)


def go_back_or_home(request):
    ref = request.META.get('HTTP_REFERER')
    if ref:
        return redirect(ref)
    else:
        return go_home(request)


def index(request):
Beispiel #48
0
if getattr(settings, 'MATERIAL_FRONTEND_AUTOREGISTER', True):
    settings.LOGIN_REDIRECT_URL = '/'

    # Register middleware
    if 'material.frontend.middleware.SmoothNavigationMiddleware' not in settings.MIDDLEWARE_CLASSES:
        settings.MIDDLEWARE_CLASSES += (
            'material.frontend.middleware.SmoothNavigationMiddleware', )

    if 'material.frontend.middleware.UnpjaxMiddleware' not in settings.MIDDLEWARE_CLASSES:
        settings.MIDDLEWARE_CLASSES += (
            'material.frontend.middleware.UnpjaxMiddleware', )

    # Register pjax template tag
    try:
        from django.template.base import add_to_builtins
        add_to_builtins("material.frontend.templatetags.pjax_tags")
    except ImportError:
        """
        Django 1.9
        """
        for engine in settings.TEMPLATES:
            if engine[
                    'BACKEND'] == 'django.template.backends.django.DjangoTemplates':
                if 'OPTIONS' not in engine:
                    engine['OPTIONS'] = {}
                if 'builtins' not in engine['OPTIONS']:
                    engine['OPTIONS']['builtins'] = []
                if "material.frontend.templatetags.pjax_tags" not in engine[
                        'OPTIONS']['builtins']:
                    engine['OPTIONS']['builtins'].append(
                        "material.frontend.templatetags.pjax_tags")
Beispiel #49
0
from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.models import User
from django.template.base import add_to_builtins
from .forms import AuthenticateForm, UserCreateForm, UserEditForm, AuthorForm, PublisherForm, LendPeriodForm, BookForm
from .models import Book, LendPeriods, QuotationFromBook, Author, Publisher, UserProfile
from .tables import BookTable, FriendTable, BookTableUser, AuthorTable, PublisherTable, PeriodsTable
from django_tables2 import RequestConfig
from django.contrib import messages
from django.utils import timezone
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .decorators.group_required import group_required
from django.db.models.base import ObjectDoesNotExist
from fandjango.decorators import facebook_authorization_required

add_to_builtins('library_app.templatetags.xextends')
add_to_builtins('library_app.templatetags.has_group')


@facebook_authorization_required
def fb_sign_up(request, what=None):
    """
    Responsible for sign in and sign up using facebook.

    :param what: string that determines whether it is sign in or sign up
    :type what: `string`
    """
    if request.method == 'POST':
        if what.__str__() == "sign_up":
            init_data = {
                'first_name':
Beispiel #50
0
SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"

# Django debug toolbar
# http://django-debug-toolbar.readthedocs.io/en/1.4/configuration.html
DEBUG_TOOLBAR_CONFIG = {
    'DISABLE_PANELS': {
        'debug_toolbar.panels.templates.TemplatesPanel',
        'debug_toolbar.panels.redirects.RedirectsPanel',
    },
}

# shortcut for in form templates
try:
    # shortcut for in form templates
    from django.template.base import add_to_builtins
    add_to_builtins('material.templatetags.material_form')
    add_to_builtins('template_debug.templatetags.debug_tags')
except ImportError:
    """
    Django 1.9.
    """
    TEMPLATES[0]['OPTIONS']['builtins'] = [
        'material.templatetags.material_form',
        'template_debug.templatetags.debug_tags'
    ]

STATIC_ROOT = os.path.join(BASE_DIR, 'deploy', 'static')
MEDIA_ROOT = os.path.join(BASE_DIR, 'deploy', 'media')

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
Beispiel #51
0
            if not code.buffer:
              codeTag = code.val.strip().split(' ',1)[0]
              if codeTag in self.autocloseCode:
                  self.buf.append('{%% end%s %%}'%codeTag)

    def attributes(self,attrs):
        return "{%% __pyjade_attrs %s %%}"%attrs


try:
    try:
        from django.template.base import add_to_builtins
    except ImportError: # Django < 1.8
        from django.template import add_to_builtins
    add_to_builtins('pyjade.ext.django.templatetags')
except ImportError:
    # Django 1.9 removed add_to_builtins and instead
    # provides a setting to specify builtins:
    # TEMPLATES['OPTIONS']['builtins'] = ['pyjade.ext.django.templatetags']
    pass

from django.utils.translation import trans_real

try:
    from django.utils.encoding import force_text as to_text
except ImportError:
    from django.utils.encoding import force_unicode as to_text

def decorate_templatize(func):
    def templatize(src, origin=None):
Beispiel #52
0
    dictionary = dictionary or {}
    if isinstance(template_name, (list, tuple)):
        t = select_template(template_name)
    else:
        t = get_template(template_name)
    if not context_instance:
        return t.render(Context(dictionary))
    # Add the dictionary to the context stack, ensuring it gets removed again
    # to keep the context_instance in the same state it started in.
    with context_instance.push(dictionary):
        return t.render(context_instance)


def select_template(template_name_list):
    "Given a list of template names, returns the first that can be loaded."
    if not template_name_list:
        raise TemplateDoesNotExist("No template names provided")
    not_found = []
    for template_name in template_name_list:
        try:
            return get_template(template_name)
        except TemplateDoesNotExist as e:
            if e.args[0] not in not_found:
                not_found.append(e.args[0])
            continue
    # If we get here, none of the templates could be loaded
    raise TemplateDoesNotExist(', '.join(not_found))


add_to_builtins('django.template.loader_tags')
Beispiel #53
0
#!/usr/bin/env python
#
#
#
# Copyright (c) 2008-2011 University of Dundee.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Author: Aleksandra Tarkowska <A(dot)Tarkowska(at)dundee(dot)ac(dot)uk>, 2012.
#

from django.template.base import add_to_builtins

add_to_builtins('omeroweb.webgateway.templatetags.defaulttags')
Beispiel #54
0

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "tests/static"),
)

SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"

# shortcut for in form templates
from django.template.base import add_to_builtins
add_to_builtins('material.templatetags.material_form')
add_to_builtins('template_debug.templatetags.debug_tags')


STATIC_ROOT = os.path.join(BASE_DIR, 'deploy/static')

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.environ.get('EMAIL')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
EMAIL_PORT = 587


try:
    from deploy.local_settings import *  # NOQA
except ImportError:
Beispiel #55
0
import datetime

from django.test import TestCase
from django import template
from django.template.base import add_to_builtins

import ttag
from ttag.tests.setup import tags, models

add_to_builtins(tags.__name__)


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


class TagExecutionTests(TestCase):

    def test_default(self):
        """
        A tag with named arguments works with or without the argument as long
        as a default value is set.
        """
        self.assertEqual(render('{% named_arg %}'),
                         'The limit is %d' %
                         tags.NamedArg._meta.args['limit'].default)

        # Reset the limit tag to have no default (and be required, which is set
        # to False if a default was given.
        tags.NamedArg._meta.args['limit'].default = None
        tags.NamedArg._meta.args['limit'].required = True