Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django URL conf without a view - to link to another domain

I'd like to be able to use the reverse url lookups in order to link to a pre-set domain e.g:

in a template:

<a href="{% url 'admin_site' %}">Admin</a>

Where the page may sit at http://www.mydomain.com/home and the admin site might be http://admin.mydomain.com - or when in dev mode, it might be http://devadmin.localhost

I can set the domain in settings using environment variables - but how might I get the URL framework to put that domain in the page template?

Two simple routes to achieve this:

  1. Just create a redirect view that might sit at somewhere like /go/admin which will just redirect to whatever domain I set up.

  2. Include my domain in the template context and rewrite the href something like <a href="{{ ADMIN_SITE }}">

Both options would work. But both have drawbacks: first one involves and extra redirect step, second one doesn't use the same url tag as other links.

like image 727
Guy Bowden Avatar asked Nov 01 '22 16:11

Guy Bowden


1 Answers

I don't think you can/should directly add external urls to your urls.py. That file is for URLs that must be resolved from the django server, so if the page is in another server... and, you want to make use of {% url %} it must be through a redirect.

I would do this:

from django.conf.urls import patterns, url
from django.views.generic import RedirectView

urlpatterns = patterns('',
    # ...

    url(r'^remote_admin/$', RedirectView.as_view(url='http://admin.mydomain.com'),
        name='remote_admin'),
    url(r'^dev_admin/$', RedirectView.as_view(url='http://devadmin.localhost'),
        name='dev_admin'),
)

Then {% url %} should work as usual:

{% url 'remote_admin' %}
like image 185
Adrián Avatar answered Nov 15 '22 07:11

Adrián