Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 796
Richard Avatar asked Jun 14 '13 15:06

Richard


People also ask

How does Django define URL pattern?

To design URLs for an app, you create a Python module informally called a URLconf (URL configuration). This module is pure Python code and is a mapping between URL path expressions to Python functions (your views). This mapping can be as short or as long as needed. It can reference other mappings.

What is dynamic URL routing in Django?

Dynamic Routing: It is the process of getting dynamic data(variable names) in the URL and then using it.


1 Answers

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.

like image 69
karthikr Avatar answered Sep 27 '22 20:09

karthikr