Login

ScriptPrefixMiddleware

Author:
shellsage
Posted:
September 2, 2009
Language:
Python
Version:
1.1
Tags:
url domain get_absolute_url host set_script_prefix
Score:
1 (after 1 ratings)

Adds http://hostname or https://hostname before every URL generated by a Django url function.

Example: Normally, something like YourModel().get_absolute_url() would return /2009/09/02/slug. However, this is not an absolute URL, because it does not include an HTTP schema or host.

With this middleware, YourModel().get_absolute_url() will return http://yourdomain.com/2009/09/02/slug.

This will also work for calls to reverse() or the {% url %} template tag.

Installation:

Drop this code into yourproject/middleware/scriptprefix.py.

Usage:

In your settings.py, add:

MIDDLEWARE_CLASSES = (
# ...
'yourproject.middleware.scriptprefix.ScriptPrefixMiddleware',
# ...
)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.core.urlresolvers import set_script_prefix

class ScriptPrefixMiddleware(object):
    """
    Set the script prefix for all requests.

    Essentially this adds the current request host to all calls to
    get_absolute_url().  Much more convenient than adding the schema and
    domain manually everywhere.

    """

    def process_request(self, request):
        schema = 'http://'
        if request.is_secure():
            schema = 'https://'
        host = request.get_host()
        if host:
            set_script_prefix('%s%s' % (schema, host))

More like this

  1. Create short URL redirects for site urls. by matt.geek.nz 6 years, 2 months ago
  2. DaGood breadcrumbs by drozzy 6 years, 3 months ago
  3. Hyperlink list filter by lifefloatsby 7 years, 3 months ago
  4. Ensure submitted slugs do not conflict with existing resolvable URLs by ElfSternberg 5 years, 10 months ago
  5. HTTPS redirections middleware with updated URL template tag by xlq 2 years, 6 months ago

Comments

Please login first before commenting.