Have you ever wondered how Django works and what components lie behind and what is happening when you run the application? You probably go to documentation or listen to good but lengthy talks given by core members of Django Framework.
I wanted to study what is happening behind the scenes of Django and came across the amazing talk by James Bennett at PyCon 2015. After learning lots of things from that I will give here a quick overview of how the application works and If you are interested in an in-depth picture then refer to the talk.
Note: This is not a structured guide, I will share a bit about every part of story as we proceed.
So we start our application by typing the command 'py manage.py runserver' what it does here is passing the runserver parameter to manage.py file which has all the commands that we use while working with django, commands like startapp, createsuperuser, and so on.
On starting server, we see messages on the prompt that server in running to a port usually localhost:8000. Now django application starting point is wsgi.py file WSGI stands for Web Server Gateway Interface. It is readable and will load the settings of projects. If you look carefully settings.py file is also not complicated it is just a list and variables. After settings are loaded the application is started. First, it will direct to the default URL that is '/'.
You can specify from where to start and you can also direct the '/' to respond with the home page. So when you request URL, it is searched with regex in urlpatterns list of urls.py file and first value that is matched with URL then associated view is returned. These views are mapped in urls.py file with function name from views.py and URL that you want for that view and pass it path() function that will be part of the list.
Views
To qualify as view block of code
- must be callable
- must take accept the HTTP request
- must return a response or raise an exception
We also pass variables in response from views and that data is showed using templates. Now few things regarding the template, django has its own but if you want you can plugin the template of your choice. It works this way there are lexers and parsers, data from any source is received like variable or database. Using regex the template is selected from string, like this is a pattern of comment and this is a pattern of variable then the token is extracted later sent to parser returns the node and nodelist based on the output generated from token then it is sent further to render() method and name suggest what it does. views are wrapped and made into transactions so either it is executed or rollback if an error occurs. views could be class-based or function-based and depending on scenario choose your format, the class base provides feature like inheritance and oops, while function based don't look scary on day one.
Now that we touched the source like a database that leads us to discuss few more topics related to it like orm, models and forms. let's discuss each.
ORM
ORM stands for object relation mapping, it helps us perform database operations without writing SQL queries provides us with functions that make it easy to use, and helps us focus on writing logic rather than thinking about database statement structure. Django has its own and it has evolved over the years and has become very useful to manage small to the medium level databases. You can write raw SQL queries also if you want to.
ORM consists of
- Model
- Manager
- QuerySet
- Query
- SQLCompiler
- Database backend
Each server different purpose and you can refer documentation or talk mentioned above to see in-depth but for a quick overview, Database backend deals with understanding what database it has to connect with it is database dependent, after that, it understands the types that the database supports an operator to commands conversions is also made possible by the backend. It has many supporting modules like database Wrapper and database Operation, it also has now a very useful thing called introspect what it does is creates a Model for you if you specify the database to be attached. So we do not need to look into the database and write a Model by mapping every column to Feild. ORM does that for us, so here reverse mapping goes from Database columns to Model fields.
SQLCompiler does translate django queries to SQL statements and each part of the query is constructed then sent to SQL for execution and we can use signals here if we want to use triggers that SQL provides.
Models
Now, let's discuss Models, they are data Table representations in-class format. The table name is Model name, Table Columns are Model fields and we can also set up foreign key constraint and other conditions as well we can override the default behavior by creating Meta class. There is the conversion of data in python from Model field to Table Columns supporter data types, django takes care of that for us. That conversion happens on every transaction.
Forms
Form consists of
- Forms
- Fields
- Widgets
- Model <-> Conversion
- Media support
The model allows us to create forms and they work closely that does not mean that ORM, Models, and Form have to exist together. There would be some use-case where you only need form but do not want to make database transactions. Forms are made of widgets, widgets correspond to each HTML form tag and then data is extracted. From also gives the option to create a custom validator or use the basics provided by django.
These were few facts regarding django framework and basic understanding of things that go behind the scenes.