2

Is it possible to have two different urls.py files for one project, using one of them all the time, but then invoking the second for development purposes?

What I want is this:

For production (and is live 24/7) I want the following links:

www.mydomain.com
www.mydomain.com/about/
www.mydomain.com/contact/

But for development (which I use the runserver now and then as I test) I want all the base links, plus a few more:

www.mydomain.com
www.mydomain.com/about/
www.mydomain.com/contact/
www.mydomain.com/secret/sauce/
www.mydomain.com/punchanella/in/the/zoo/
www.mydomain.com/me/too/

So effectively the outside world does not even know that my extra links exist since they don't have any access to them.

Is this even possible?

Garfonzo
  • 499
  • 2
  • 18

2 Answers2

2

I would do it like this

In your settings.py set the following

LOCAL_DEV = True

then in your urls.py

from django.conf import settings
if settings.LOCAL_DEV:
  urlpatterns = patterns('',
   #
   # all your other urls here for dev
   #
)
Mike
  • 22,310
  • 7
  • 56
  • 79
  • Branching for different envs in your code is not what I would consider a best practice, yet it does seem to be the overwhelmingly most popular option for this particular use case, which is disappointing. – odigity May 30 '22 at 16:21
1

Django defines the ROOT_URLCONF parameter for this use case. Example for different URL sets for development and production environment: create two different urls modules, for example urls_dev and urls_prod with different urlpatterns. Project structure:

myproj
├── models.py
├── views.py
├── ...
├── urls_dev.py
└── urls_prod.py

In your settings, redefine ROOT_URLCONF depending on what environment you are currently in:

# settings.py

if os.environ.get('DEVELOPMENT', None):
    ROOT_URLCONF = 'myproj.urls_dev'
else:
    ROOT_URLCONF = 'myproj.urls_prod'

or even split the single settings into two different modules, settings_dev and settings_prod, each defining its own ROOT_URLCONF. Then start the server with the selected settings:

$ django-admin runserver --settings=myproj.settings_dev
hoefling
  • 186
  • 6
  • 1
    I like this answer. Instead of branching in your code, use an env var or CLI option to set the correct settings file which drives the rest of the changes. – odigity May 30 '22 at 16:23