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

30👍

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

👤Keith

7👍

If your app is going to display anything to the user with its own url pattern, it should probably have its own urls.py file. So in your base urls file, you’d have something in your urlpatterns like url(r'', include('path.to.app.urls')). Then your app’s urls.py file would have a pattern like url(r'^$', 'path.to.app.views.view').

👤Jamey

6👍

If the app is mostly self-contained and having its own place in the URL hierarchy makes sense, then it should have its own urls.py. But even if it does exist, it’s still only a guideline to the project developer unless include() is used to graft it into the project URLconf.

Leave a comment