Exemplo n.º 1
0
def _get_object_navigation_links(context,
                                 menu_name=None,
                                 links_dict=object_navigation):
    request = Variable('request').resolve(context)
    current_path = request.META['PATH_INFO']
    current_view = resolve_to_name(current_path)
    context_links = []

    # Don't fudge with the original global dictionary
    links_dict = links_dict.copy()

    # Preserve unicode data in URL query
    previous_path = smart_unicode(
        urllib.unquote_plus(
            smart_str(request.get_full_path())
            or smart_str(request.META.get('HTTP_REFERER', u'/'))))
    query_string = urlparse.urlparse(previous_path).query
    parsed_query_string = urlparse.parse_qs(query_string)

    try:
        """
        Override the navigation links dictionary with the provided
        link list
        """
        navigation_object_links = Variable('overrided_object_links').resolve(
            context)
        if navigation_object_links:
            return [
                link for link in
                resolve_links(context, navigation_object_links, current_view,
                              current_path, parsed_query_string)
            ]
    except VariableDoesNotExist:
        pass

    try:
        """
        Check for and inject a temporary navigation dictionary
        """
        temp_navigation_links = Variable('temporary_navigation_links').resolve(
            context)
        if temp_navigation_links:
            links_dict.update(temp_navigation_links)
    except VariableDoesNotExist:
        pass

    try:
        links = links_dict[menu_name][current_view]['links']
        for link in resolve_links(context, links, current_view, current_path,
                                  parsed_query_string):
            context_links.append(link)
    except KeyError:
        pass

    obj, object_name = get_navigation_object(context)

    try:
        links = links_dict[menu_name][type(obj)]['links']
        for link in resolve_links(context, links, current_view, current_path,
                                  parsed_query_string):
            context_links.append(link)
    except KeyError:
        pass

    return context_links
Exemplo n.º 2
0
 def __init__(self, obj, context_var):
     self.obj = Variable(obj)
     self.context_var = context_var
Exemplo n.º 3
0
 def __init__(self, obj, var_name, with_feedback):
     self.obj = Variable(obj)
     self.var_name = var_name
     self.with_feedback = with_feedback
Exemplo n.º 4
0
 def __init__(self, title, url_node):
     self.title = Variable(title)
     self.url_node = url_node
Exemplo n.º 5
0
 def __init__(self, *args, **kwargs):
     self.args = [Variable(arg) for arg in args]
     self.kwargs = dict([(k, Variable(arg)) for k, arg in kwargs.items()])
Exemplo n.º 6
0
 def __init__(self, actions, varname=None):
     self.actions = Variable(actions)
     self.varname = varname
Exemplo n.º 7
0
 def __init__(self, record, fieldset, crosslinks):
     self.record = Variable(record)
     self.fieldset = Variable(fieldset) if fieldset else None
     self.crosslinks = Variable(crosslinks) if crosslinks else None
Exemplo n.º 8
0
 def __init__(self, user, event, context_var):
     self.user = Variable(user)
     self.event = Variable(event)
     self.context_var = context_var
Exemplo n.º 9
0
    def render(self, context):
        tags = u''
        query = u''
        user = AnonymousUser()
        limit = 3
        order = 'next_upcoming'
        event_type = ''
        group = u''
        start_dt = u''

        randomize = False

        if 'start_dt' in self.kwargs:
            try:
                start_dt = datetime.strptime(
                    self.kwargs['start_dt'].replace('"', '').replace('"', ''),
                    '%m/%d/%Y-%H:%M')
            except ValueError:
                pass

        if 'random' in self.kwargs:
            randomize = bool(self.kwargs['random'])

        if 'tags' in self.kwargs:
            try:
                tags = Variable(self.kwargs['tags'])
                tags = str(tags.resolve(context))
            except:
                tags = self.kwargs['tags']

            tags = tags.replace('"', '')
            tags = tags.split(',')

        if 'user' in self.kwargs:
            try:
                user = Variable(self.kwargs['user'])
                user = user.resolve(context)
            except:
                user = self.kwargs['user']
                if user == "anon" or user == "anonymous":
                    user = AnonymousUser()
        else:
            # check the context for an already existing user
            # and see if it is really a user object
            if 'user' in context:
                if isinstance(context['user'], User):
                    user = context['user']

        if 'limit' in self.kwargs:
            try:
                limit = Variable(self.kwargs['limit'])
                limit = limit.resolve(context)
            except:
                limit = self.kwargs['limit']

        limit = int(limit)

        if 'query' in self.kwargs:
            try:
                query = Variable(self.kwargs['query'])
                query = query.resolve(context)
            except:
                query = self.kwargs['query']  # context string

        if 'order' in self.kwargs:
            try:
                order = Variable(self.kwargs['order'])
                order = order.resolve(context)
            except:
                order = self.kwargs['order']

        if 'type' in self.kwargs:
            try:
                event_type = Variable(self.kwargs['type'])
                event_type = event_type.resolve(context)
            except:
                event_type = self.kwargs['type']

        if 'group' in self.kwargs:
            try:
                group = Variable(self.kwargs['group'])
                group = str(group.resolve(context))
            except:
                group = self.kwargs['group']

            try:
                group = int(group)
            except:
                group = None

        filters = get_query_filters(user, 'events.view_event')
        items = Event.objects.filter(filters)
        if user.is_authenticated:
            if not user.profile.is_superuser:
                items = items.distinct()

        if event_type:
            if ',' in event_type:
                items = items.filter(type__name__in=event_type.split(','))
            else:
                items = items.filter(type__name__iexact=event_type)

        if tags:  # tags is a comma delimited list
            # this is fast; but has one hole
            # it finds words inside of other words
            # e.g. "prev" is within "prevent"
            tag_queries = [Q(tags__iexact=t.strip()) for t in tags]
            tag_queries += [Q(tags__istartswith=t.strip() + ",") for t in tags]
            tag_queries += [Q(tags__iendswith=", " + t.strip()) for t in tags]
            tag_queries += [Q(tags__iendswith="," + t.strip()) for t in tags]
            tag_queries += [
                Q(tags__icontains=", " + t.strip() + ",") for t in tags
            ]
            tag_queries += [
                Q(tags__icontains="," + t.strip() + ",") for t in tags
            ]
            tag_query = reduce(or_, tag_queries)
            items = items.filter(tag_query)

        if hasattr(self.model, 'group') and group:
            items = items.filter(groups=group)
        if hasattr(self.model, 'groups') and group:
            items = items.filter(groups__in=[group])

        objects = []

        if start_dt:
            items = items.filter(start_dt__gte=start_dt)

        # exclude private events
        items = items.filter(enable_private_slug=False)

        # if order is not specified it sorts by relevance
        if order:
            if order == "next_upcoming":
                if not start_dt:
                    # Removed seconds and microseconds so we can cache the query better
                    now = datetime.now().replace(second=0, microsecond=0)
                    items = items.filter(start_dt__gt=now)
                items = items.order_by("start_dt", '-priority')
            elif order == "current_and_upcoming":
                if not start_dt:
                    now = datetime.now().replace(second=0, microsecond=0)
                    items = items.filter(
                        Q(start_dt__gt=now) | Q(end_dt__gt=now))
                items = items.order_by("start_dt", '-priority')
            elif order == "current_and_upcoming_by_hour":
                now = datetime.now().replace(second=0, microsecond=0)
                today = datetime.now().replace(second=0,
                                               hour=0,
                                               minute=0,
                                               microsecond=0)
                tomorrow = today + timedelta(days=1)
                items = items.filter(
                    Q(start_dt__lte=tomorrow) & Q(end_dt__gte=today)).extra(
                        select={
                            'hour': 'extract( hour from start_dt )'
                        }).extra(select={
                            'minute': 'extract( minute from start_dt )'
                        }).extra(where=["extract( hour from start_dt ) >= %s"],
                                 params=[now.hour])
                items = items.distinct()
                items = items.order_by('hour', 'minute', '-priority')
            else:
                items = items.order_by(order)

        if randomize:
            items = list(items)
            objects = random.sample(items, min(len(items), limit))
        else:
            objects = items[:limit]

        context[self.context_var] = objects
        return ""
Exemplo n.º 10
0
    def get_bound_field(self, context):
        # First we try to resolve the {% formfield player.name %} syntax were
        # player is a model instance.
        if '.' in self.field_variable_name:
            form = self.get_form_instance(context)
            instance_name_in_template, field_name = \
                self.field_variable_name.split('.', -1)
            instance_in_template = Variable(
                instance_name_in_template).resolve(context)
            # it could be form.my_field
            if isinstance(instance_in_template, models.Model):
                instance_from_view = form.instance
                if type(instance_from_view) == UndefinedFormModel:
                    raise ValueError(
                        'Template contains a formfield, but '
                        'you did not set form_model on the Page class.'
                    )
                elif type(instance_in_template) != type(instance_from_view):
                    raise ValueError(
                        'In the page class, you set form_model to {!r}, '
                        'but in the template you have a formfield for '
                        '"{}", which is a different model.'.format(
                            type(instance_from_view),
                            instance_name_in_template,
                        )
                    )
                # we should ensure that Player and Group have readable
                # __repr__
                elif instance_in_template != instance_from_view:
                    raise ValueError(
                        "You have a formfield for '{}' "
                        "({!r}), which is different from "
                        "the expected model instance "
                        "({!r}).".format(
                            instance_name_in_template,
                            instance_in_template,
                            form.instance))
                try:
                    return form[field_name]
                except KeyError:
                    raise ValueError(
                        "'{field_name}' was used as a formfield in the template, "
                        "but was not included in the Page's 'form_fields'".format(
                            field_name=field_name)) from None

        # Second we try to resolve it to a bound field.
        # No field found, so we return None.
        bound_field = Variable(self.field_variable_name).resolve(context)

        # We assume it's a BoundField when 'as_widget', 'as_hidden' and
        # 'errors' attribtues are available.
        if (
                not hasattr(bound_field, 'as_widget') or
                not hasattr(bound_field, 'as_hidden') or
                not hasattr(bound_field, 'errors')):
            raise ValueError(
                "The given variable '{variable_name}' ({variable!r}) is "
                "neither a model field nor a form field.".format(
                    variable_name=self.field_variable_name,
                    variable=bound_field))
        return bound_field
Exemplo n.º 11
0
from django.conf import settings
from django.db import models, connections
from django.utils.translation import ugettext as _
from django.utils.http import urlquote
from django.utils.encoding import iri_to_uri, force_text
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.text import capfirst

from freppledb.common.models import User
from freppledb import VERSION

MAX_CRUMBS = 10

register = Library()
variable_title = Variable("title")
variable_request = Variable("request")
variable_popup = Variable("is_popup")

#
# A tag to create breadcrumbs on your site
#


class CrumbsNode(Node):
    r'''
  A generic breadcrumbs framework.

  Usage in your templates:
  {% crumbs %}
Exemplo n.º 12
0
 def resolve_bound_field(self, context):
     bound_field = Variable(self.field_variable_name).resolve(context)
     return bound_field
Exemplo n.º 13
0
 def test_no_log_when_variable_exists(self):
     Variable('article.section').resolve({'article': {'section': 'News'}})
     self.assertIsNone(self.test_handler.log_record)
Exemplo n.º 14
0
 def render(self, context):
     request = Variable('request').resolve(context)
     view_name = resolve_to_name(request.META['PATH_INFO'])
     context[self.var_name] = sidebar_templates.get(view_name, [])
     return ''
Exemplo n.º 15
0
def var_or_none(x):
    if x is not None:
        return Variable(x)
Exemplo n.º 16
0
 def __init__(self, tags_to_add, tags_to_remove):
     self.tags_to_add = [Variable(tag) for tag in tags_to_add]
     self.tags_to_remove = [Variable(tag) for tag in tags_to_remove]
Exemplo n.º 17
0
 def __init__(self, actor, varname=None):
     self.actor = Variable(actor)
     self.varname = varname
Exemplo n.º 18
0
 def __init__(self, lang_code, variable):
     self.lang_code = Variable(lang_code)
     self.variable = variable
Exemplo n.º 19
0
 def __init__(self, nodelist, expire_time_var, fragment_name, vary_on):
     self.nodelist = nodelist
     self.expire_time_var = Variable(expire_time_var)
     self.fragment_name = fragment_name
     self.vary_on = vary_on
Exemplo n.º 20
0
 def __init__(self, languages, variable):
     self.languages = Variable(languages)
     self.variable = variable
Exemplo n.º 21
0
 def __init__(self, title, url_node, render_func=create_crumb):
     self.title = Variable(title)
     self.url_node = url_node
     self.render_func = render_func
Exemplo n.º 22
0
 def __init__(self, filter_expression, noop):
     self.noop = noop
     self.filter_expression = filter_expression
     if isinstance(self.filter_expression.var, basestring):
         self.filter_expression.var = Variable(u"'%s'" %
                                               self.filter_expression.var)
Exemplo n.º 23
0
 def __init__(self, url, varname, value):
     self.url = Variable(url)
     self.varname = Variable(varname)
     self.value = Variable(value)
Exemplo n.º 24
0
 def __init__(self, promotion):
     self.promotion_var = Variable(promotion)
Exemplo n.º 25
0
 def __init__(self, id_):
     self.id = Variable(id_)
Exemplo n.º 26
0
 def __init__(self, item_to_be_rendered):
     self.item_to_be_rendered = Variable(item_to_be_rendered)
Exemplo n.º 27
0
 def parse_cvars(self, pairs):
     cvars = []
     for vname, vobj in [pair.split("=") for pair in pairs]:
         cvars.append((vname, Variable(vobj)))
     return cvars
Exemplo n.º 28
0
 def __init__(self, nodes, roots):
     self.nodes = nodes
     self.roots = Variable(roots)
     self.tree_query_set = None
Exemplo n.º 29
0
 def __init__(self, obj):
     self.obj = Variable(obj)
 def __init__(self, field):
     self.field = Variable(field)