skip to navigation
skip to content

Not Logged In

django-spurl 0.6.1

A Django template library for manipulating URLs.

# django-spurl

### Super URLs for Django

;c =\
__| _/
/.. ____ \
/ {% spurl %} \
( / \--\_>/-/'._ )
\-;_/\__;__/ _/ _/
/ /-._.--\ \_
// / /| \ \ \
/ | | | \; | \ \
/ / | :/ \: \ \_\
/ | /.'| /: | \ \
| | |--| . |--| \_\
/ _/ \ | : | /___--._) \
|_(---'-| >-'-| | '-'
/_/ \_\

**Spurl** is a Django template library for manipulating URLs. It's built on top of Zachary Voase's excellent [urlobject]

Authored by [Jamie Matthews] and some great [contributors]

[![Latest Version]]
[![Build Status]]

## Installation

Either checkout ``spurl`` from GitHub, or install using pip:

pip install django-spurl

Add ``spurl`` to your `INSTALLED_APPS`:

Finally, whenever you want to use Spurl in a template, you need to
load its template library:

{% load spurl %}

## Usage

Spurl is **not** a replacement for Django's built-in ``{% url %}``
template tag. It is a general-purpose toolkit for manipulating URL
components in templates. You can use it alongside ``{% url %}`` if you
like (see below).

Spurl provides a single template tag, called (surprisingly enough),
``spurl``. You call it with a set of ``key=value`` keyword arguments,
which are described fully below.

To show some of the features of Spurl, we'll go over a couple of
simple example use cases.

### Adding query parameters to URLs

Say you have a list of external URLs in your database. When you create
links to these URLs in a template, you need to add a ````
query parameter to each. The simple way to do this might be:

{% for url, title in list_of_links %}
{{ title }}
{% endfor %}

The problem here is that you don't know in advance if the URLs stored
in your database *already* have query parameters. If they do, you'll
generate malformed links like ````.

Spurl can fix this. Because it knows about the components of a URL, it
can add parameters onto an existing query, if there is one.

{% for url, title in list_of_links %}
{{ title }}
{% endfor %}

Note that **when you pass a literal string to Spurl, you have to wrap
it in double quotes**. If you don't, Spurl will assume it's a variable
name and try to look it up in the template's context.

### SSL-sensitive external URLs.

Suppose your site needs to display a gallery of images, the URLs of
which have come from some third-party web API. Additionally, imagine
your site needs to run both in secure and non-secure mode - the same
content is available at both ``https`` or ``http`` URLs (depending on
whether a visitor is logged in, say). Some browsers will complain
loudly (displaying "Mixed content warnings" to the user) if the page
being displayed is ``https`` but some of the assets are ``http``. Spurl
can fix this.

{% for image_url in list_of_image_urls %}

{% endfor %}

This will take the image URL you supply and replace the scheme
component (the ``http`` or ``https`` bit) with the correct version,
depending on the return value of ``request.is_secure()``. Note that
the above assumes you're using a ``RequestContext`` so that
``request`` is available in your template.

### Using alongside ``{% url %}``

Notice that Spurl's functionality doesn't overlap with Django's
built-in ``{% url %}`` tag. Spurl doesn't know about your urlconf, and
doesn't do any URL reversing. In fact, Spurl is mostly useful for
manipulating **external** URLs, rather than URLs on your own
site. However, you can easily use Spurl with ``{% url %}`` if you need
to. You just have to use the ``as`` keyword to put your reversed URL
in a template variable, and then pass this to Spurl. As it's a
relative path (rather than a full URL) you should pass it using the
``path`` argument. For example, say you want to append some query
parameters to a URL on your site:

{% url your_url_name as my_url %}
Click here!

There is another way to use Spurl with ``{% url %}``, see *Embedding
template tags* below.

### Available arguments

Below is a full list of arguments that Spurl understands.

#### base

If you pass a ``base`` argument to Spurl, it will parse its contents
and use this as the base URL upon which all other arguments will
operate. If you *don't* pass a ``base`` argument, Spurl will generate a
URL from scratch based on the components that you pass in separately.

#### scheme

Set the scheme component of the URL. Example:

{% spurl base="" scheme="ftp" %}

This will return ````

See also: ``scheme_from``, below.

#### host

Set the host component of the URL. Example:

{% spurl base="" host="" %}

This will return ````

See also: ``host_from``, below.

#### path

Set the path component of the URL. Example:

{% spurl base="" path="/different/" %}

This will return ````

See also: ``path_from``, below.

#### add_path

Append a path component to the existing path. You can add multiple
``add_path`` calls, and the results of each will be combined. Example:

{% spurl base=STATIC_URL add_path="javascript" add_path="lib" add_path="jquery.js" %}

This will return ````
(assuming ``STATIC_URL`` is set to ````)

See also: ``add_path_from``, below.

#### fragment

Set the fragment component of the URL. Example:

{% spurl base="" fragment="myfragment" %}

This will return ````

See also: ``fragment_from``, below.

#### port

Set the port component of the URL. Example:

{% spurl base="" port="8080" %}

This will return ````

See also: ``port_from``, below.

#### query

Set the query component of the URL. Example:

{% spurl base="" query="foo=bar&bar=baz" %}

This will return ````

The ``query`` argument can also be passed a dictionary from your template's context.

def my_view(request):
my_query_params = {'foo': 'bar', 'bar': 'baz'}
return render(request, 'path/to/template.html', {'my_query_params': my_query_params})


{% spurl base="" query=my_query_params %}

This will return ````

Finally, you can pass individual template variables to the query. To
do this, Spurl uses Django's template system. For example:

{% spurl base="" query="foo={{ variable_name }}" %}

See also: ``query_from``, below.

#### add_query

Append a set of parameters to an existing query. If your base URL
might already have a query component, this will merge the existing
parameters with your new ones. Example:

{% spurl base="" add_query="bar=baz" %}

This will return ````

You can add multiple ``add_query`` calls, and the results of each will be combined:

{% spurl base="" add_query="foo=bar" add_query="bar=baz" %}

This will return ````

Like the ``query`` argument above, the values passed to ``add_query`` can
also be dictionaries, and they can contain Django template variables.

See also: ``add_query_from``, below.

#### set_query

Appends a set of parameters to an existing query, overwriting existing
parameters with the same name. Otherwise uses the exact same syntax as

See also: ``set_query_from``, below.

#### toggle_query

Toggle the value of one or more query parameters between two possible
values. Useful when reordering list views. Example:

{% spurl base=request.get_full_path toggle_query="sort=ascending,descending" %}

If the value of ``request.get_full_path()`` doesn't have a ``sort``
parameter, one will be added with a value of ``ascending`` (the first
item in the list is the default). If it already has a ``sort``
parameter, and it is currently set to ``ascending``, it will be set to
``descending``. If it's already set to ``descending``, it will be set
to ``ascending``.

You can also specify the options as a dictionary, mapping the
parameter name to a two-tuple containing the values to
toggle. Example:


SORT_PARAM = 'sort'
ASCENDING = 'ascending'
DESCENDING = 'descending'

def my_view(request):

object_list = MyModel.objects.order_by('-somefield')
object_list = MyModel.objects.order_by('somefield')

return render(request, 'path/to/template.html', {
'object_list': object_list,


Reverse order

#### remove_query_param

Remove a query parameter from an existing query:

{% spurl base="" remove_query_param="foo" %}

This will return ````

Again, you can add multiple ``remove_query_param`` calls, and the results will be combined:

{% spurl base="" remove_query_param="foo" remove_query_param="bar" %}

This will return ````

#### secure

Control whether the generated URL starts with ``http`` or
``https``. The value of this argument can be a boolean (``True`` or
``False``), if you're using a context variable. If you're using a
literal argument here, it must be a quoted string. The strings
``"True"`` or ``"on"`` (case-insensitive) will be converted to
``True``, any other string will be converted to ``False``. Example:

{% spurl base="" secure="True" %}

This will return ````

#### autoescape

By default, Spurl will escape its output in the same way as Django's
template system. For example, an ``&`` character in a URL will be
rendered as ``&``. You can override this behaviour by passing an
``autoescape`` argument, which must be either a boolean (if passed
from a template variable) or a string. The strings ``"True"`` or
``"on"`` (case-insensitive) will be converted to ``True``, any other
string will be converted to ``False``.

### Added bonus: ``_from`` parameters

As well as those listed above, Spurl provides a family of parameters
for *combining* URLs. Given a base URL to start with, you can copy a
component from another URL. These arguments expect to be passed a full
URL (or anything that can be understood by ``URLObject.parse``). This
URL will be parsed, and then the component in question will be
extracted and combined with the base URL.

Below is a full list of the available ``_from`` methods. They have
identical semantics to their counterparts above (except they expect a
full URL, not just a URL component).

* `query_from`
* `add_query_from`
* `set_query_from`
* `scheme_from`
* `host_from`
* `path_from`
* `add_path_from`
* `fragment_from`
* `port_from`


{% spurl base=" path_from="" %}

This will return ````

### Building a URL without displaying it

Like Django's ``{% url %}`` tag, Spurl allows you to insert the
generated URL into the template's context for later use. Example:

{% spurl base="" secure="True" as secure_url %}

The secure version of the url is {{ secure_url }}


### Embedding template tags

As mentioned above, Spurl uses Django's template system to
individually parse any arguments which can be passed strings. This
allows the use of syntax such as:

{% spurl base="" add_query="foo={{ bar }}" %}

This works fine for variable and filters, but what if we want to use
other template tags *inside* our Spurl tag? We can't nest ``{%`` and
``%}`` tokens inside each other, because Django's template parser would
get very confused. Instead, we have to escape the inner set of tag
markers with backslashes:

{% spurl base="" add_query="next={\% url home %\}" %}

Note that any tags or filters loaded in your template are
automatically available in the nested templates used to render each
variable. This means we can do:

{% load url from future %}
{% spurl base="{\% url 'home' %\}" %}

Be careful with your quotation marks! If you use double-quotes to
surround the nested template, you have to use single quotes inside it.

**Warning!** This functionality only exists to serve the most complex of use cases, and is extremely magical (and probably a bad idea). You may prefer to use:

{% url "home" as my_url %}
{% spurl base=my_url %}

## Development

To contribute, fork the repository, make your changes, add some tests,
commit, push, and open a pull request.

### How to run the tests

Spurl is tested with [nose] Clone the
repository, then run ``pip install -r requirements.txt`` to install
nose and Django into your virtualenv. Then, simply type ``nosetests`` to
find and run all the tests.

## (Un)license

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.


For more information, please refer to <http:""/>

## Artwork credit

Superman ASCII art comes from <http:"" art="" superman="">  
File Type Py Version Uploaded on Size
django-spurl-0.6.1.tar.gz (md5, pgp) Source 2015-07-14 13KB
  • Downloads (All Versions):
  • 80 downloads in the last day
  • 1995 downloads in the last week
  • 6836 downloads in the last month