Richard
Richard

Reputation: 65600

Django: conditional URL patterns?

I'd like to use a different robots.txt file depending on whether my server is production or development.

To do this, I would like to route the request differently in urls.py:

urlpatterns = patterns('',
   // usual patterns here
)

if settings.IS_PRODUCTION: 
  urlpatterns.append((r'^robots\.txt$', direct_to_template, {'template': 'robots_production.txt', 'mimetype': 'text/plain'}))
else:
  urlpatterns.append((r'^robots\.txt$', direct_to_template, {'template': 'robots_dev.txt', 'mimetype': 'text/plain'}))

However, this isn't working, because I'm not using the patterns object correctly: I get AttributeError at /robots.txt - 'tuple' object has no attribute 'resolve'.

How can I do this correctly in Django?

Upvotes: 6

Views: 7565

Answers (2)

user11784
user11784

Reputation: 33

In Django 1.8 and up, adding URLs is simple:

if settings.IS_PRODUCTION:
    urlpatterns += [
      url(r'^robots\.txt$', direct_to_template, {'template': 'robots_production.txt', 'mimetype': 'text/plain'}),
    ]

Upvotes: 1

karthikr
karthikr

Reputation: 99680

Try this:

if settings.IS_PRODUCTION: 
  additional_settings = patterns('',
     (r'^robots\.txt$', direct_to_template, {'template': 'robots_production.txt', 'mimetype': 'text/plain'}),
  )
else:
  additional_settings = patterns('',
      (r'^robots\.txt$', direct_to_template, {'template': 'robots_dev.txt', 'mimetype': 'text/plain'}),
  )

urlpatterns += additional_settings

Since you are looking to append tuple types , append does not work.
Also, pattern() calls the urlresolver for you. In your case you were not, hence the error.

Upvotes: 11

Related Questions