How to Execute a pre_save Signal in Django
In this article, we show how to execute a pre_save signal in Django.
So, first thing, what is a pre_save signal?
A pre_save signal is a function that is carried out before a database table (model) is saved.
A pre_save signal basically signals for a function to occur before the database table (model) is saved.
When would we want to use a pre_save signal?
Usually a pre_save signal is used when you want to save a value to a database that is generated by a function.
Let's use youtube as an example.
Every time a video is uploaded, youtube generates a random 11-character string for the video. It uses a function to create a random 11-character string to identify the video and then stores this string in the database and then the database is saved.
This is a perfect situation of when you would use a pre_save signal in Django.
Any time you want to use a function to generate a value that you want stored in the database before it's saved can utilize a pre_save signal.
So now that you know what a pre_save signal is and when to use it, let's go over an actual example in Django code. This will be quick.
In the following code below, we generate a random 6-digit text code that can be used
to authenticate an account.
So this is a model that uses a pre_save signal for the code field of the model.
So in order to use a pre_save signal in Django, we must import pre_save from django.db.models.signals
Also since this code will be running a function from the utils.py file, we need to import the function from the utils.py file.
Basically, we define a pre_save function, pre_save_text_msg_code().
This function will set the code field of the particular instance of the model to the value generated from the unique_text_msg_code_generator() function (which is in another file, the utils.py file).
So we created the function but we haven't connected it to the pre_save signal mechanism.
So we do this using the line, pre_save.connect(pre_save_txt_msg_code, sender= UserTextMessage)
The sender is the model you are dealing with. We're saying that before the pre_save signal is executed, we want to execute the unique_text_msg_code function.
And this is all that is required to execute a pre_save signal in Django.
Of course in this article, we had an external function in another python file. However, you could put the function that the pre_save signal will execute in the models.py file.
Again, a pre_save signal is a signal that calls for a function to be executed before the model is saved. It is used often when a value that goes into a certain field of a model needs to be generated by a function, such as a random password, a random text code, a random string ID, etc.
And this is how to execute a pre_save signal in Django.
Related Resources
How to Randomly Select From or Shuffle a List in Python