MVC Pattern and Django
The MVC pattern
Before advent of MVC frameworks, web programming mixed database code with the main code of the page. If you have programmed for some time in language like PHP you already did this to some extent. This problem is not particular to PHP; In fact in most server-side languages the code is shared between atleast three language: Python (or PHP), SQL, HTML.
The MVC pattern was created to separate business logic from representation. MVC is the most popular architecture in use today. Many popular frameworks like Ruby on Rails, Laravel, Codeigniter and even Django uses it. The MVC architecture divides an application into three layers: Model, View and Controller. Let's discuss each of them separately.
Models: Models represents how data is organized in the database. In other words in MVC pattern we use models to define our tables in the database. We also use models to define relationship between other models.
Views: A view is what you see when you visit a site. For example a blog post, a contact form are all examples of views. A View contains all the information that will be eventually sent to the client i.e a web browser. Generally views are HTML documents.
Controllers: Controller controls the flow of information. When you request a page that request is passed to Controller then it uses programmed logic to decide what information is needed to pulled from the database and what information should it pass to the view. Controller is the heart of MVC because it acts as a glue between models and views.
Here is a rundown of steps involved in an MVC blog application.
1) Web browser or client sends the request to the web server, asking the server to display a blog post.
2) The request received by the server is passed to the controller of the application.
3) The controller asks the model to fetch the blog post.
4) The model sends the blog post to the controller.
5) The controller then passes the blog post data to the view.
6) The view uses blog post data to create an html page.
7) At last the controller returns the HTML content to the client.
The MVC pattern not only helps us to create and maintain complex application. It really shines when it comes of separation of concerns. For example, In a web development company, there are web designers and there are developers. The job of web designers is to create views. The developers take these views and incorporate them with models and controllers.
Django follows MVC pattern very closely but it uses slightly different terminology. Django is essentially a MTV (Model-Template-View) pattern. Django uses templates for views and views for controller. In other words in Django views are called templates and controllers are called views. Hence our HTML code will be in templates and python code will be in views and models.