Design Patterns in Django 1.3
In the previous post (part 1.2), We have discussed a few Design Patterns. Here, we will continue our journey of DDPs. We have completed the Model and Form DDPs. Now its time to discuss some more DDPs (View, Template).
3. View
In Django, View is a responsible entity to accept a user request and generate the required response. It could be a function or class having a special class method named as_view().
3.1 Access Controlled Views
We need to provide access to various pages based on user profiles. For example logged-in user, anonymous user, admin, etc. The use of Decorators is one of the Solutions. When we want to restrict a page only to be used by logged-in users, we can apply @login_required Decorator.
3.2 Context Enhancer
Several Views share a few variables, which are common throughout the web app. We can have a global utility class which will contain all the shared variables at a central location. Example: Header and Footer data, which is common for all the views of the web app.
3.3 Services
Human is not the only requestor to a particular web application. In many cases, another web app or machine could be a requestor. Example bots, web-crawlers, web-scrappers. HTML is a very heavyweight response which is not ideal for machine-to-machine (M-2-M) communication. JSON or XML formats are well-suited formats to handle it. Django REST framework provides the functionality required to perform fast and robust M-2-M communication.
4. Template
Templates are the third major block of MTV architecture of Django. Template designing is a very critical and essential task as these are the point of contact with users. Templates must be organized in a way that can handle complex data and provide an attractive view to the user at the same time.
4.1 Template Inheritance Tree
Various code blocks are used repeatedly throughout the web application. We can create generalized sub-pages that can be fitted as required. Example: Header and Footer block, which is common for all the pages of the web application. Menu bar for a logged-user, which is required in all the pages for a logged-in user.
4.2 The Active Link
The navigation bar is one of the essential parts of a web application. Users must we aware of his current location on the web application. We can highlight the particular link of the navigation bar on which the user is currently visiting.
That’s it for this post. We have completed the DDPs as mentioned in the Book of Arun Ravindran. For detailed study please read the book and follow the code examples available at https://github.com/DjangoPatternsBook/superbook.
[Code Author: Arun Ravindran (GitHub id: arocks)]
THANK YOU……..