Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) ?

like image 391
Parag Avatar asked Feb 17 '12 05:02

Parag


People also ask

Why we use URLs py in Django?

A request in Django first comes to urls.py and then goes to the matching function in views.py. Python functions in views.py take the web request from urls.py and give the web response to templates. It may go to the data access layer in models.py as per the queryset.

What is the purpose of URLs py?

This tells Django to search for URL patterns in the file books/urls.py . For example, A URL request to /books/crime/ will match with the second URL pattern. As a result, Django will call the function views.

How many apps can a Django project have?

Django comes with six built-in apps that we can examine.

How do I add a URL to a Django project?

project/urls.py is the one that django uses, so you have to import to project/urls.py. Which means, that you have to state your imports in project/urls.py. The imported urls.py file must also define a valid urlconf, named urlpatterns. I think I had to restart the server (plus forgot the include), works now!


2 Answers

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

like image 172
Keith Avatar answered Sep 19 '22 17:09

Keith


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').

like image 26
Jamey Avatar answered Sep 19 '22 17:09

Jamey