- Author:
- shellsage
- Posted:
- September 2, 2009
- Language:
- Python
- Version:
- 1.1
- 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
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.