MVC

Let’s dive in with a quick example that demonstrates the difference between the previous approach and that undertaken using a Web framework. Here’s how you might write the previous CGI code using Django:

Image 2 Image 3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Don’t worry about the particulars of how this works just yet — we just want you to get a feel for the overall design. The main thing to note here is the separation of concerns:

  • The models.py file contains a description of the database table, as a Python class. This is called a model. Using this class, you can create, retrieve, update, and delete records in your database using simple Python code rather than writing repetitive SQL statements.
  • The views.py file contains the business logic for the page, in the latest_books() function. This function is called a view.
  • The urls.py file specifies which view is called for a given URL pattern. In this case, the URL /latest/ will be handled by the latest_books() function.
  • The latest_books.html is an HTML template that describes the design of the page.

Taken together, these pieces loosely follow the Model-View-Controller (MVC) design pattern. Simply put, MVC defines a way of developing software so that the code for defining and accessing data (the model) is separate from request routing logic (the controller), which in turn is separate from the user interface (the view).

A key advantage of such an approach is that components are loosely coupled. That is, each distinct piece of a Django-powered Web application has a single key purpose and can be changed independently without affecting the other pieces. For example, a developer can change the URL for a given part of the application without affecting the underlying implementation. A designer can change a page’s HTML without having to touch the Python code that renders it. A database administrator can rename a database table and specify the change in a single place, rather than having to search and replace through a dozen files.

Back to Tutorial

What Is a Web Framework?
Django evolution

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?