Should every django app within a project have it's own urls.py?

Parag picture Parag · Feb 17, 2012 · Viewed 19.6k times · Source

I am working on a django project which will contain several apps. Each app will have their own set of models and views.

Should each app also define their own url's with a urls.py or maybe a function. What is the best practice for defining urls of apps within a django project, and integrating these urls with the main urls.py (root url conf) ?

Answer

Keith picture Keith · Feb 17, 2012

It depends. If you're dealing with a tiny website with one app, you can keep all the expressions in the same urls.py.

However, when you're dealing with a more complicated site with truly separate apps, I prefer the following structure:

  • myapp
    • admin.py
    • forms.py
    • models.py
    • urls.py
    • views.py
  • manage.py
  • settings.py
  • urls.py

Don't forget each folder needs it's own __ init__.py

# urls.py
from django.conf.urls.defaults import *
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    # Notice the expression does not end in $, 
    # that happens at the myapp/url.py level
    (r'^myapp/', include('myproject.myapp.urls')),
)

# myapp/urls.py
from django.conf.urls.defaults import *

urlpatterns = patterns('myproject.myapp.views',
    (r'^$', 'default_view',
    (r'^something/$', 'something_view',
)

You also may want to look at Class-based Generic Views