Build the _complete_ aboslute URI...

42 views
Skip to first unread message

Jens Diemer

unread,
Oct 31, 2007, 4:06:58 AM10/31/07
to django...@googlegroups.com

With get_absolute_url() [1] we can build a URL of a model entry. The Problem is,
this is not really a _complete_ URL. The protocol and domain is absent.

I implemented this:

-------------------------------------------------------------------------------
def get_absolute_uri(self):
"""
returned the complete absolute URI (with the domain/host part)
"""
url = self.get_absolute_url()

if os.environ.get("HTTPS") == "on":
protocol = "https"
else:
protocol = "http"

domain = os.environ.get("SERVER_NAME")
if not domain:
domain = os.environ.get("HTTP_HOST")
if not domain:
# Can't build the complete uri without the domain ;(
# e.g. running the django development server
return url

return "%s://%s%s" % (protocol, domain, url)
-------------------------------------------------------------------------------

I think it's not a good idea to get information from os.environ. This only works
with Apache.
The better way is to use request.META or directly request.build_absolute_uri().
But IMHO i can't get the request object in the model.

I can't use Site.objects.get_current().domain [2], because i didn't use the Site
framework. And this is not a good idea: The protocoll is always "http".

Any better idea?

[1] <http://www.djangoproject.com/documentation/model-api/#get-absolute-url>
[2]
<http://www.djangoproject.com/documentation/sites/#getting-the-current-domain-for-full-urls>


--
Mfg.

Jens Diemer


----
A django powered CMS: http://www.pylucid.org

guettli...@thomas-guettler.de

unread,
Oct 31, 2007, 9:30:49 AM10/31/07
to django...@googlegroups.com
On Wed, Oct 31, 2007 at 09:06:58AM +0100, Jens Diemer wrote:
>
>
> With get_absolute_url() [1] we can build a URL of a model entry. The Problem is,
> this is not really a _complete_ URL. The protocol and domain is absent.
>
> I implemented this:
> ...

The URL is absolute, since it starts with a slash. Maybe this helps you:

Look at request.build_absolute_uri() (http/__init__.py)

Thomas

--
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

Jens Diemer

unread,
Oct 31, 2007, 10:20:14 AM10/31/07
to django...@googlegroups.com
guettli...@thomas-guettler.de schrieb:

> On Wed, Oct 31, 2007 at 09:06:58AM +0100, Jens Diemer wrote:
>>
>> With get_absolute_url() [1] we can build a URL of a model entry. The Problem is,
>> this is not really a _complete_ URL. The protocol and domain is absent.
>>
>> I implemented this:
>> ...
>
> The URL is absolute, since it starts with a slash. Maybe this helps you:
>
> Look at request.build_absolute_uri() (http/__init__.py)

Yes, but i can't get the request object in the model :( So this is not a solution :(

Reply all
Reply to author
Forward
0 new messages