def auth(request):
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)
        return HttpResponseRedirect(url('home'))
    else:
        return HttpResponseRedirect(url('invalid'))
Beispiel #2
0
def make_notification(data):
    """
    This function make a notify to user for that propouse receive data param that is a dictionary with the keys
    user_id: Int pk of user to make the notify
    text: String for the body of notify
    level: Int to represent the level of importance of notify
    :param data: Python dictionary
    :return: None
    """
    if not data or data is None:
        return
    user = User.objects.filter(pk=data["user_id"])
    if not user or user is None:
        return
    n = Notify()
    n.user = user.first()
    n.level = data["level"] or 0
    n.main_text = data["text"]
    n.save()
    """
    If the user of the notify have activated the flag to receive email when have a new notify, then try send and email
    """
    if user.perfil_usuario.notificacion_email:
        message_body = """
        Te ha llegado una nueva notificación que se ha generado debido ha algún evento del sistema que te involucra,
        puedes ver todas las notificaciones desde este enlace 
        """ + url("notifies")
        send_mail(_("Tienes una nueva notificación"),
                  _(message_body),
                  settings.DEFAULT_FROM_EMAIL, [user.email],
                  fail_silently=False)
Beispiel #3
0
def absurl(parser, token, node_cls=AbsoluteURLNode):
    """Just like {% url %} but ads the domain of the current site."""
    node_instance = url(parser, token)
    return node_cls(view_name=node_instance.view_name,
                    args=node_instance.args,
                    kwargs=node_instance.kwargs,
                    asvar=node_instance.asvar)
Beispiel #4
0
def absurl(parser, token, node_cls=AbsoluteURLNode):
    """Just like {% url %} but ads the domain of the current site."""
    node_instance = url(parser, token)
    return node_cls(view_name=node_instance.view_name,
        args=node_instance.args,
        kwargs=node_instance.kwargs,
        asvar=node_instance.asvar)
Beispiel #5
0
def sph_url2(*args, **kwargs):
    try:
        node = defaulttags.url(*args, **kwargs)
        return SphURLNode(node.view_name, node.args, node.kwargs, node.asvar)
    except TemplateSyntaxError:
        log.error('Error while resolving url for %r / %r', args, kwargs, [str(x) for x in args])
        return TextNode('')
Beispiel #6
0
def fullurl(parser, token):
    """Return an absolute URL (including the scheme and domain) matching the
    given view with its parameters.

    This is meant to be identical to the built-in tag `url`, except that it
    always returns an absolute URL with the scheme and authority parts.

    For example, take this `url` tag:

        {% url "articles:article" slug="hello" %}

    This could return:

        /articles/hello

    This is considered an absolute URL because it begins with a forward-slash,
    however, it is not an absolute absolute URL, because it does not include
    the scheme and authority parts.

    Compare with this `fullurl` tag:

        {% fullurl "articles:article" slug="hello" %}

    This returns:

        http://example.com/articles/hello

    """
    return FullURLNode(defaulttags.url(parser, token))
Beispiel #7
0
def full_url(parser, token):
    """Spits out the full URL"""
    url_node = url(parser, token)
    f = url_node.render
    url_node.render = lambda context: _get_host_from_context(context) + f(
        context)
    return url_node
Beispiel #8
0
def saneurl(parser, token):
    """
    Allows variable/filters as view names in url tag.
    
    {% saneurl some_variable %}
    """
    return SaneURLNode(url(parser, token))
Beispiel #9
0
def absurl(parser, token):
    node = url(parser, token)
    return AbsoluteURLNode(
        view_name=node.view_name,
        args=node.args,
        kwargs=node.kwargs,
        asvar=node.asvar
    )
Beispiel #10
0
def absurl(parser, token):
    node = url(parser, token)
    return AbsoluteURLNode(
        view_name=node.view_name,
        args=node.args,
        kwargs=node.kwargs,
        asvar=node.asvar
    )
Beispiel #11
0
 def render(self, context):
     from django.template import TOKEN_BLOCK, Token
     
     resolved_named_url = self.named_url.resolve(context)
     contents = u'url ' + resolved_named_url
     
     urlNode = url(self.parser, Token(token_type=TOKEN_BLOCK, contents=contents))
     return urlNode.render(context)
def url_optional(parser, token):    
    """
     creates the default URLNode, then routes it to the Optional resolver with the same properties
     by first creating the URLNode, the parsing stays in django core where it belongs.     
    """ 
    
    urlnode = url(parser, token)
    return URLNodeOptional(urlnode.view_name, urlnode.args, urlnode.kwargs, urlnode.asvar)
def url_or_back(parser, token):
    """
    Returns the result of the default tag ``url`` unless it is the same target
    as the HTTP_REFERER header in which case a simple
        'javascript:history.back()'
    saves a useless hit to the server.
    """
    return UrlOrBackNode(url(parser, token))
def transurl(parser, token):
    """
    Returns an absolute URL matching given view with its parameters.

    See django.templatetags.future.url and django.template.defaulttags.URLNode
    """
    from django.template.defaulttags import url
    return TransURLNode.from_urlnode(url(parser, token))
Beispiel #15
0
def sph_url2(*args, **kwargs):
    try:
        node = defaulttags.url(*args, **kwargs)
        return SphURLNode(node.view_name, node.args, node.kwargs, node.asvar)
    except TemplateSyntaxError:
        log.error('Error while resolving url for %r / %r', args, kwargs,
                  [str(x) for x in args])
        return TextNode('')
Beispiel #16
0
 def render(self, context):
     from django.template import TOKEN_BLOCK, Token
     
     resolved_named_url = self.named_url.resolve(context)
     contents = u'url ' + resolved_named_url
     
     urlNode = url(self.parser, Token(token_type=TOKEN_BLOCK, contents=contents))
     return urlNode.render(context)
Beispiel #17
0
def disqus_url(parser, token):
    url_instance = url(parser, token)

    return DisqusURLNode(
        view_name=url_instance.view_name,
        args=url_instance.args,
        kwargs=url_instance.kwargs,
        asvar=url_instance.asvar
    )
Beispiel #18
0
def absurl(parser, token):
    """Just like {% url %} but ads the domain of the current site."""
    # invoke url setup just to parse the arguments.
    node = url(parser, token)
    # then pass the parsed args to the actual node instance
    return AbsoluteURLNode(view_name=node.view_name,
                           args=node.args,
                           kwargs=node.kwargs,
                           asvar=node.asvar)
Beispiel #19
0
def abs_url(parser, token, node_cls=AbsoluteURLNode):
    """Just like {% url %} but creates an absolute URL."""
    node_instance = url(parser, token)
    return node_cls(
        view_name=node_instance.view_name,
        args=node_instance.args,
        kwargs=node_instance.kwargs,
        asvar=node_instance.asvar,
    )
def menuitem(parser, token):
    bullseye = '_bullseye'
    head, sep, tail = token.contents.partition(bullseye)
    token.contents = ' '.join([head.rstrip(), tail.lstrip()])
    nodelist = parser.parse(('endmenuitem',))
    parser.delete_first_token()
    node = url(parser, token)
    node.render = markup(node.render, nodelist, bool(sep))
    return node
Beispiel #21
0
def absolute_url(parser, token, node_cls=AbsoluteURLNode):
    """
    Just like {% url %} but adds the domain from settings.ABSOLUTE_HOST.
    """
    node_instance = url(parser, token)

    return node_cls(view_name=node_instance.view_name,
                    args=node_instance.args,
                    kwargs=node_instance.kwargs,
                    asvar=node_instance.asvar)
    def render(self, context):
        from django.template import TOKEN_BLOCK, Token

        resolved_named_url = self.named_url.resolve(context)
        if django.VERSION >= (1, 3):
            contents = 'url "%s"' % resolved_named_url
        else:
            contents = 'url %s' % resolved_named_url

        urlNode = url(self.parser, Token(token_type=TOKEN_BLOCK, contents=contents))
        return urlNode.render(context)
def suburl(parser, token, node_cls=SubdomainAbsoluteURLNode):
    """Just like {% url %} but ads the domain of the current site."""
    subdomain_context = token.split_contents()[2]
    
    token.contents = token.contents.replace(subdomain_context, '')
    node_instance = url(parser, token)
    return node_cls(view_name=node_instance.view_name,
        args=node_instance.args,
        kwargs=node_instance.kwargs,
        asvar=node_instance.asvar,
        subdomain_context=subdomain_context)
Beispiel #24
0
def absolute(parser, token):
    '''
    Returns a full absolute URL based on the request host.

    This template tag takes exactly the same paramters as url template tag.
    '''
    node = url(parser, token)
    return AbsoluteUrlNode(view_name=node.view_name,
                           args=node.args,
                           kwargs=node.kwargs,
                           asvar=node.asvar)
    def render(self, context):
        from django.template import TOKEN_BLOCK, Token

        resolved_named_url = self.named_url.resolve(context)
        if django.VERSION >= (1, 3):
            contents = 'url "%s"' % resolved_named_url
        else:
            contents = 'url %s' % resolved_named_url

        urlNode = url(self.parser, Token(token_type=TOKEN_BLOCK, contents=contents))
        return urlNode.render(context)
Beispiel #26
0
def breadcrumb_last_url(parser, token):
    bits = token.split_contents()
    if len(bits) == 2:
        return breadcrumb(parser, token)

    # Extract our extra title parameter
    title = bits.pop(1)
    token.contents = ' '.join(bits)

    url_node = url(parser, token)

    return UrlBreadcrumbNode(title, url_node, True)
    def render(self, context):
        from django.template import TOKEN_BLOCK, Token

        resolved_named_url = self.named_url.resolve(context)
        if django.VERSION >= (1, 3):
            tokens = resolved_named_url.split(' ')
            base = tokens[0]
            args = tokens[1:]
            contents = u'url "{0}" {1}'.format(base, ' '.join(args))
        else:
            contents = u'url {0}'.format(resolved_named_url)
        urlNode = url(self.parser, Token(token_type=TOKEN_BLOCK, contents=contents))
        return urlNode.render(context)
def blogurl(parser, token):
    """
    Compatibility tag to allow django-fluent-blogs to operate stand-alone.
    Either the app can be hooked in the URLconf directly, or it can be added as a pagetype of django-fluent-pages.
    For the former, URL resolving works via the normal '{% url "viewname" arg1 arg2 %}' syntax.
    For the latter, the URL resolving works via '{% appurl "viewname" arg1 arg2 %}' syntax.
    """
    if HAS_APP_URLS:
        from fluent_pages.templatetags.appurl_tags import appurl
        return appurl(parser, token)
    else:
        from django.template.defaulttags import url
        return url(parser, token)
Beispiel #29
0
def url_timeslot(parser, token):
    """
    Wrapper around url templatetag which inserts a timeslot argument if a timeslot is present.

    :param parser:
    :param token:
    :return:
    """
    node = url(parser, token)  # default url parser
    ts = get_timeslot()
    if ts:
        node.args.append(FilterExpression(token=str(ts.pk), parser=parser))
    return node
Beispiel #30
0
def ancestor(parser, token):
    # If there is only one argument (2 including tag name)
    # parse it as a variable
    bits = token.split_contents()
    if len(bits) == 2:
        arg = parser.compile_filter(bits[1])
    else:
        arg = None

    # Also pass all arguments to the original url tag
    url_node = url(parser, token)

    return AncestorNode(url_node, arg=arg)
Beispiel #31
0
def site(parser, token):
    '''
    Returns a full absolute URL based on the current site.

    This template tag takes exactly the same paramters as url template tag.
    '''
    node = url(parser, token)
    return SiteUrlNode(
        view_name=node.view_name,
        args=node.args,
        kwargs=node.kwargs,
        asvar=node.asvar
    )
Beispiel #32
0
def ancestor(parser, token):
    # If there is only one argument (2 including tag name)
    # parse it as a variable
    bits = token.split_contents()
    if len(bits) == 2:
        arg = parser.compile_filter(bits[1])
    else:
        arg = None

    # Also pass all arguments to the original url tag
    url_node = url(parser, token)

    return AncestorNode(url_node, arg=arg)
Beispiel #33
0
def blogurl(parser, token):
    """
    Compatibility tag to allow django-fluent-blogs to operate stand-alone.
    Either the app can be hooked in the URLconf directly, or it can be added as a pagetype of django-fluent-pages.
    For the former, URL resolving works via the normal '{% url "viewname" arg1 arg2 %}' syntax.
    For the latter, the URL resolving works via '{% appurl "viewname" arg1 arg2 %}' syntax.
    """
    if HAS_APP_URLS:
        from fluent_pages.templatetags.appurl_tags import appurl
        return appurl(parser, token)
    else:
        from django.template.defaulttags import url
        return url(parser, token)
def old_style_url(parser, token):
    global error_on_old_style_url_tag

    bits = token.split_contents()
    view = bits[1]

    if error_on_old_style_url_tag:
        _error("Old style url tag used (only reported once per file): {%% %s %%}" % (" ".join(bits)), token)
        error_on_old_style_url_tag = False

    if view[0] in "\"'" and view[0] == view[-1]:
        _error("Old style url tag with quotes around view name: {%% %s %%}" % (" ".join(bits)), token)

    return defaulttags.url(parser, token)
    def render(self, context):
        from django.template import TOKEN_BLOCK, Token

        resolved_named_url = self.named_url.resolve(context)
        # edit hts SpectralAngel
        if django.VERSION >= (1, 3):
            tokens = resolved_named_url.split(' ')
            base = tokens[0]
            args = tokens[1:]
            contents = u'url "{0}" {1}'.format(base, ' '.join(args))
        else:
            contents = u'url {0}'.format(resolved_named_url)
        ## edit
        urlNode = url(self.parser, Token(token_type=TOKEN_BLOCK, contents=contents))
        return urlNode.render(context)
Beispiel #36
0
def relurl(parser, token, node_cls=RelativeURLNode):
    """Use like the url templatetag, but provide the request path as the first
    argument and this templatetag will return a relative url."""
    old_token = token
    contents = old_token.split_contents()
    request_path = contents.pop(1)
    new_token = Token(old_token.token_type, ' '.join(contents))
    node_instance = url(parser, new_token)
    node_instance.request_path = request_path
    node = node_cls(view_name=node_instance.view_name,
                    args=node_instance.args,
                    kwargs=node_instance.kwargs,
                    asvar=node_instance.asvar)
    node.request_path = request_path
    return node
Beispiel #37
0
def breadcrumb_url(parser, token):
	"""
	Render breadcrumbs in the form of:
		{% breadcrumb 'Breadcrumb title' url args %}
	"""

	contents = token.split_contents()
	if len(contents) == 2:
		return breadcrumb(parser, token) # Shortcut to normal breadcrumbs

	title = contents.pop(1)
	token.contents = ' '.join(contents)

	url = django_defaulttags.url(parser, token)
	return UrlBreadcrumbNode(title, url)
Beispiel #38
0
def relurl(parser, token, node_cls=RelativeURLNode):
    """Use like the url templatetag, but provide the request path as the first
    argument and this templatetag will return a relative url."""
    old_token = token
    contents = old_token.split_contents()
    request_path = contents.pop(1)
    new_token = Token(old_token.token_type, ' '.join(contents))
    node_instance = url(parser, new_token)
    node_instance.request_path = request_path
    node = node_cls(view_name=node_instance.view_name,
        args=node_instance.args,
        kwargs=node_instance.kwargs,
        asvar=node_instance.asvar)
    node.request_path = request_path
    return node
Beispiel #39
0
def group_url(parser, token):
    """
    A proxy wrapper for the Django 'url' tag for URLs pointing to pages within a CosinnusGroup.
    This tag is aware of which type of group is being pointed to and will automatically chose
    the correct URL path specific for the group type, as configured with group_model_registry.py.
    
    Otherwise this uses the django 'url' tag definition.
    """
    
    urlnode = url(parser, token)
    
    if not "group" in urlnode.kwargs:
        raise TemplateSyntaxError("'group_url' tag requires a group kwarg!")
    
    return GroupURLNode(urlnode.view_name, urlnode.args, urlnode.kwargs, urlnode.asvar)
Beispiel #40
0
def do_repo_url(parser, token):
    func_name, view_name, token_parts = token.contents.split(' ', 2)

    token_parts = token_parts.split(' ', 1)
    if len(token_parts) > 1:
        repo_obj_name = token_parts[0]
        new_token = token_parts[1]
    else:
        repo_obj_name = token_parts[0]
        new_token = ''

    return url(
        parser,
        template.Token(
            token.token_type, '%s %s %s.user.username %s.slug %s' %
            (func_name, view_name, repo_obj_name, repo_obj_name, new_token)))
Beispiel #41
0
def url_fqdn(parser, token):
    """
    Acts like 'url(), but returns with FQDN of current context.  Takes optional 'sitedata' label to override.

    Use like the following:
    {% url_fqdn 'name-of-url' %}
    {% url_fqdn 'name-of-url' sitedata='djangohunter' %}
    """

    node = url(parser, token)

    return SiteDataURLNode(
        view_name=node.view_name,
        args=node.args,
        kwargs=node.kwargs,
        asvar=node.asvar,
    )
Beispiel #42
0
def locale_url(parser, token):
    """
    Renders the url for the view with another locale prefix. The syntax is
    like the 'url' tag, only with a locale before the view.

    Examples:
      {% locale_url "de" cal.views.day day %}
      {% locale_url "nl" cal.views.home %}
      {% locale_url "en-gb" cal.views.month month as month_url %}
    """
    bits = token.split_contents()
    if len(bits) < 3:
        raise TemplateSyntaxError("'%s' takes at least two arguments:"
                                  " the locale and a view" % bits[0])
    urltoken = Token(token.token_type, bits[0] + ' ' + ' '.join(bits[2:]))
    urlnode = defaulttags.url(parser, urltoken)
    return LocaleURLNode(bits[1], urlnode)
Beispiel #43
0
def asset_url(parser, token, node_cls=AssetURLNode):
    """
        Just like the "url" templatetag, except replaces the filename part of
        the url path with the versioned filename pulled from the asset manifest
        generated by webpack.

        Example:
          {% asset_url 'sentry-media' 'sentry' 'dist/sentry.css' %}
          =>  "/_static/sentry/dist/sentry.74d127b78dc7daf2c51f.css"
    """

    node_instance = url(parser, token)

    return node_cls(view_name=node_instance.view_name,
                    args=node_instance.args,
                    kwargs=node_instance.kwargs,
                    asvar=node_instance.asvar)
def locale_url(parser, token):
    """
    Renders the url for the view with another locale prefix. The syntax is
    like the 'url' tag, only with a locale before the view.

    Examples:
      {% locale_url "de" cal.views.day day %}
      {% locale_url "nl" cal.views.home %}
      {% locale_url "en-gb" cal.views.month month as month_url %}
    """
    bits = token.split_contents()
    if len(bits) < 3:
        raise TemplateSyntaxError("'%s' takes at least two arguments:"
                " the locale and a view" % bits[0])
    urltoken = Token(token.token_type, bits[0] + ' ' + ' '.join(bits[2:]))
    urlnode = defaulttags.url(parser, urltoken)
    return LocaleURLNode(bits[1], urlnode)
Beispiel #45
0
def do_repo_url(parser, token):
    func_name, view_name, token_parts = token.contents.split(' ', 2)

    token_parts = token_parts.split(' ', 1)
    if len(token_parts) > 1:
        repo_obj_name = token_parts[0]
        new_token = token_parts[1]
    else:
        repo_obj_name = token_parts[0]
        new_token = ''

    return url(parser, template.Token(token.token_type, '%s %s %s.user.username %s.slug %s' % (
        func_name,
        view_name,
        repo_obj_name,
        repo_obj_name,
        new_token
    )))
Beispiel #46
0
def active_urls_builder(parser, token):

	link_id = None
	query_params = []

	bits = token.split_contents()

	if LINK_RX.match(bits[1]):
		link_id = bits[1]
		bits = [bits[0]] + bits[2:]

	if QUERY_PARAM_SEPARATOR in bits:
		query_params_start = bits.index(QUERY_PARAM_SEPARATOR)
		query_params = bits[query_params_start + 1:]
		bits = bits[:query_params_start]

	print '!!', token.contents, bits, ' '.join(bits)
	url_node = url(parser, Token(token.token_type, ' '.join(bits), token.position, token.lineno))

	return ActiveUrlsBuilderNode(url_node, link_id, query_params)
def breadcrumb_url(parser, token):
    """
    Same as breadcrumb
    but instead of url context variable takes in all the
    arguments URL tag takes.
        {% breadcrumb "Title of breadcrumb" person_detail person.id %}
        {% breadcrumb person.name person_detail person.id %}
    """

    bits = token.split_contents()
    if len(bits) == 2:
        return breadcrumb(parser, token)

    # Extract our extra title parameter
    title = bits.pop(1)
    token.contents = " ".join(bits)

    url_node = url(parser, token)

    return UrlBreadcrumbNode(title, url_node)
def facebook_url(parser, token):
    """
    Works exactly like the default url tag, except the final url is replaced
    with its facebook canvas equivalent if it's in the canvas app.

    Refer to https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#url
    for more information on how to use this tag.
    """

    # The {% url %} tag's function generates a URLNode.  The URLNode's render
    # function handles generating the proper url.  We're going to move the
    # the render method and replace it with a new render method.  The new
    # method will call the old one and then adjust the url before returning.
    URLNode_obj = url(parser, token)
    URLNode_obj.old_render = URLNode_obj.render
    URLNode_obj.render = types.MethodType(
        replacement_URLNode_render_method,
        URLNode_obj,
        URLNode)
    return URLNode_obj
Beispiel #49
0
def ancestor(parser, token):
    bits = token.split_contents()

    exact = False

    if len(bits) >= 2:
        arg = parser.compile_filter(bits[1])

        # check last bits for the exact=True|False
        extra_context = token_kwargs(bits[-1:], parser, support_legacy=True)
        if 'exact' in extra_context:
            token.contents = u" ".join(bits[:-1])
        exact = extra_context.get('exact', False)
    else:
        arg = None

    # Also pass all arguments to the original url tag
    url_node = url(parser, token)

    return AncestorNode(url_node, arg=arg, exact=exact)
Beispiel #50
0
def breadcrumb_url(parser, token):
	"""
	Same as breadcrumb
	but instead of url context variable takes in all the
	arguments URL tag takes.
		{% breadcrumb "Title of breadcrumb" person_detail person.id %}
		{% breadcrumb person.name person_detail person.id %}
	"""

	bits = token.split_contents()
	if len(bits)==2:
		return breadcrumb(parser, token)

	# Extract our extra title parameter
	title = bits.pop(1)
	token.contents = ' '.join(bits)

	url_node = url(parser, token)

	return UrlBreadcrumbNode(title, url_node)
Beispiel #51
0
def ifancestor(parser, token):
    """
    Returns the contents of the tag if the provided path consitutes the
    base of the current pages path.

    There are two ways to provide arguments to this tag. Firstly one may
    provide a single argument that starts with a forward slash. e.g.

        {% ifancestor '/path/to/page' %}...{% endifancestor}
        {% ifancestor path_variable %}...{% endifancestor}

    In this case the provided path will be used directly.

    Alternatively any arguments accepted by the standard "url" tag may
    be provided. They will be passed to the url tag and the resultant
    path will be used. e.g.

        {% ifancestor 'core:model:detail' model.pk %}...{% endifancestor}

    Ultimately the provided path is matched against the path of the
    current page. If the provided path is found at the root of the current
    path it will be considered an anscestor, and the contents of this tag
    will be rendered.

    """
    # Grab the contents between
    contents = parser.parse(('endifancestor', ))
    parser.delete_first_token()

    # If there is only one argument (2 including tag name)
    # parse it as a variable
    bits = token.split_contents()
    if len(bits) == 2:
        arg = parser.compile_filter(bits[1])
    else:
        arg = None

    # Also pass all arguments to the original url tag
    url_node = url(parser, token)

    return AncestorNode(url_node, arg=arg, contents=contents)
Beispiel #52
0
def ifancestor(parser, token):
    """
    Returns the contents of the tag if the provided path consitutes the
    base of the current pages path.

    There are two ways to provide arguments to this tag. Firstly one may
    provide a single argument that starts with a forward slash. e.g.

        {% ifancestor '/path/to/page' %}...{% endifancestor}
        {% ifancestor path_variable %}...{% endifancestor}

    In this case the provided path will be used directly.

    Alternatively any arguments accepted by the standard "url" tag may
    be provided. They will be passed to the url tag and the resultant
    path will be used. e.g.

        {% ifancestor 'core:model:detail' model.pk %}...{% endifancestor}

    Ultimately the provided path is matched against the path of the
    current page. If the provided path is found at the root of the current
    path it will be considered an anscestor, and the contents of this tag
    will be rendered.

    """
    # Grab the contents between
    contents = parser.parse(('endifancestor',))
    parser.delete_first_token()

    # If there is only one argument (2 including tag name)
    # parse it as a variable
    bits = token.split_contents()
    if len(bits) == 2:
        arg = parser.compile_filter(bits[1])
    else:
        arg = None

    # Also pass all arguments to the original url tag
    url_node = url(parser, token)

    return AncestorNode(url_node, arg=arg, contents=contents)
Beispiel #53
0
def ancestor(parser, token):
    """Checks whether a given URL is the "ancestor" of the current request's
    path.

    In other words, this tag is used the see whether the current page (the
    current request's path) is a "child" of some other URL (in the URL
    structure). This ability is useful for discovering whether a navigation
    element is "selected" or not.

    Usage:
    {% load ancestor %}

    If the argument to the ancestor tag matches the start of the current page's
    URL, it outputs "selected":

    Using a string as the URL path:
    {% ancestor '/arbitrary/path/' %}

    Or using variables, filters, etc.:
    {% ancestor some_variable|somefilter %}

    Or url reverse resolution:
    {% ancestor 'core:model_detail' model.pk %}

    Adapted from https://github.com/marcuswhybrow/django-lineage
    """
    # If there is only one argument (2 including tag name), parse it as a
    # variable
    bits = token.split_contents()
    if len(bits) == 2:
        arg = parser.compile_filter(bits[1])
    else:
        arg = None

    # Also pass all arguments to the original url tag
    url_node = url(parser, token)

    return AncestorNode(url_node, arg=arg)
Beispiel #54
0
def ancestor(parser, token):
    """Checks whether a given URL is the "ancestor" of the current request's
    path.

    In other words, this tag is used the see whether the current page (the
    current request's path) is a "child" of some other URL (in the URL
    structure). This ability is useful for discovering whether a navigation
    element is "selected" or not.

    Usage:
    {% load ancestor %}

    If the argument to the ancestor tag matches the start of the current page's
    URL, it outputs "selected":

    Using a string as the URL path:
    {% ancestor '/arbitrary/path/' %}

    Or using variables, filters, etc.:
    {% ancestor some_variable|somefilter %}

    Or url reverse resolution:
    {% ancestor 'core:model_detail' model.pk %}

    Adapted from https://github.com/marcuswhybrow/django-lineage
    """
    # If there is only one argument (2 including tag name), parse it as a
    # variable
    bits = token.split_contents()
    if len(bits) == 2:
        arg = parser.compile_filter(bits[1])
    else:
        arg = None

    # Also pass all arguments to the original url tag
    url_node = url(parser, token)

    return AncestorNode(url_node, arg=arg)
Beispiel #55
0
def t_url(parser, token):
    exp = token.split_contents()
    new_content = exp[0] + ' ' + exp[1]
    args = {}
    arg_names = {}
    for i in range(len(exp) - 2):
        argname = ''.join([random.choice('1234567890')
                           for j in range(10)])  # 'xp_tag_arg%d'% i
        args[argname] = '<%= this.' + exp[i + 2] + ' %>'
        arg_names[argname] = argname
        new_content += ' ' + argname
    token.contents = new_content
    tagged = url(parser, token)
    old_render = tagged.render

    def new_render(context):
        rendered = old_render(Context(arg_names))
        for arg in args:
            rendered = rendered.replace(arg, args[arg])
        return rendered

    tagged.render = new_render
    return tagged
Beispiel #56
0
def site(parser, token):
    '''
    Returns a full absolute URL based on the current site.

    This template tag takes exactly the same paramters as url template tag,
    plus an optional "site" argument to force usage of a given Site object::

        {% site "my_view" site my_site_obj %}
    '''
    bits = token.split_contents()
    if len(bits) > 2 and bits[2] == 'site':
        site = parser.compile_filter(bits[3])
        token = Token(token.token_type, ' '.join(bits[:2] + bits[4:]),
                      token.position, token.lineno)
    else:
        site = None

    node = url(parser, token)

    return SiteUrlNode(site=site,
                       view_name=node.view_name,
                       args=node.args,
                       kwargs=node.kwargs,
                       asvar=node.asvar)
Beispiel #57
0
def noprefix_url(parser, token):
    """
    Returns an absolute URL matching given view with its parameters, with any
    path prefix from the WSGI request stripped.
    """
    return NoPrefixURLNode(url(parser, token))