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) ?
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.
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.
Django comes with six built-in apps that we can examine.
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!
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:
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
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With