Now’s a good time to highlight a key philosophy behind URLconfs and behind Django in general: the principle of loose coupling. Simply put, loose coupling is a software-development approach that values the importance of making pieces interchangeable. If two pieces of code are loosely coupled, then changes made to one of the pieces will have little or no effect on the other.
Django’s URLconfs are a good example of this principle in practice. In a Django web application, the URL definitions and the view functions they call are loosely coupled – i.e., the decision of what the URL should be for a given function, and the implementation of the function itself, reside in two separate places.
For example, consider our current_datetime view. If we wanted to change the URL for the application – say, to move it from /time/ to /current-time/– we could make a quick change to the URLconf, without having to worry about the view itself. Similarly, if we wanted to change the view function – altering its logic somehow – we could do that without affecting the URL to which the function is bound. Furthermore, if we wanted to expose the current-date functionality at several URLs, we could easily take care of that by editing the URLconf, without having to touch the view code.
In this example, our current_datetime is available at two URLs. It’s a contrived example, but this technique can come in handy:
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/]
URLconfs and views are loose coupling in action. I’ll continue to point out examples of this important philosophy throughout the book.
, hello), url(r'^time/]
URLconfs and views are loose coupling in action. I’ll continue to point out examples of this important philosophy throughout the book.
, current_datetime), url(r'^another-time-page/]
URLconfs and views are loose coupling in action. I’ll continue to point out examples of this important philosophy throughout the book.
, current_datetime),
]
URLconfs and views are loose coupling in action. I’ll continue to point out examples of this important philosophy throughout the book.