MVC Pattern and Django
The MVC pattern #
Before the advent of MVC frameworks, web programming mixed database code with the server side code of the page. If you have programmed for some time in a 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 at least three languages, for example, 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 the following three layers:
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 database tables as well as the relationships between them.
Views: A view is what you see when you visit a site. For example, a blog post, a contact form etc, 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 the controller then it uses programmed logic to decide what information is needed to pull from the database and what information should it pass to the view. The controller is the heart of the MVC architecture because it acts as a glue between models and views.
Here is a rundown of steps involved in an MVC blog application.
Web browser or client sends the request to the web server, asking the server to display a blog post.
The request received by the server is passed to the controller of the application.
The controller asks the model to fetch the blog post.
The model sends the blog post to the controller.
The controller then passes the blog post data to the view.
The view uses blog post data to create an HTML page.
At last, the controller returns the HTML content to the client.
The MVC pattern not only helps us to create and maintain a complex application. It really shines when it comes to 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 MTV #
Django follows MVC pattern very closely but it uses slightly different terminology. Django is essentially an MTV (Model-Template-View) framework. Django uses the term 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.