Package: django-email-signals
Django Email SignalsA Django application that provides functionality to create signals via the admin panel which will send emails based on some changes to some models.The application allows you to set your own constraints and email templates and aims to achieve this with minimal configuration.SectionsDjango Email SignalsSectionsUse CasesUsage ExampleCreating the base signalSetting the signal constraintsInstallationSetupAdding SignalsPlaygroundTestingUse CasesAdmins are able to setup signals/emails themselvesIf an admin user has requested for an email to be sent when something happens on the database, what do we do? We developers create a new signal, set any constraints, create the email templates, piece everything together, create unit tests and then deploy. Relatively simple, but still time-consuming especially when there are multiple signals to set up for various changes. This quickly becomes a quite lengthy process.This application aims to solve this by providing a way for admins to create these signals themselves rather than having to request the feature and wait for deployment. This is a great way to ease the pressure off developers whilst giving admins the ability to get results quickly.How would an admin know what fields to enter for the params?The application validates the form before saving but also provides autocomplete for the fields.Quickly prototyping and testing an email templateCreating and testing templates for some bigger teams can be a time-consuming process. This is particularly true when the request is from someone who for whatever reason cannot view your screen and relies on you deploying to a test environment to be able to test the template.The process then can become a bit tedious. Ever been in a scenario where you deploy some code to test, have it reviewed, have to tweak some code, redeploy it, and have the process repeated a few times?This application aims to solve this by providing a way for admins to create the HTML content themselves using a rich text editor. This allows admins to quickly prototype and test the email content themselves. Once ready, all they need to do is click on "show source code", and send that sweet source code to you.Usage ExampleLet us imagine that we want to notify a particular team whenever a new order is placed on our website.Creating the base signalWe would start off by setting the following signal:In this screenshot we notice a couple of things.Themodelhas been set to "sample_app | order". For this example we have created an order model (can be found inexample/sample_app/models.py) and we have setsignal typetopost save.This means that we are creating a post save signal on the order model.In this example, we have entered values for the plain text and HTML content fields. You will notice that just like we do with templates, we are able to add placeholders for context using the curly braces.We have used these in the following way:Order ID: {{ instance.id }}
Customer Name {{ instance.customer.id }}
Customer Email {{ instance.customer.email }}As this signal relates to theOrdermodel,instancerepresents a singleOrderinstance.When the email is sent, the placeholders will be replaced with the actual context values.It is important to note that the only context available isinstance, and so any other context must be accessible via theinstanceobject.This is one way to provide template context. If you prefer, you are instead able to provide a value fortemplatefield which is a path to a template file.We can also see that we have setmailing listtonew_order_mailing_list. In our order model, we have a correspondingnew_order_mailing_listmethod which returns a list of emails. This means, this particular email will be sent to the emails returned byOrder.new_order_mailing_list. By creating various methods containing different lists of emails, we effectively have a way of creating different mailing lists. Alternatively, we can just use a list of comma separated emails for the mailing list.Before we start to add any constraints, we nee to save the signal. This will make setting signal constraints easy as it will allow the autocomplete feature to help us. If you are worried about the time between saving the signal and setting the signal constraints, you can always set theactiveflag to false beforehand. This will prevent any email from being sent.Setting the signal constraintsWe can now set the constraints for the signal. We will create two constraints:Must be a new instance (created == True).Customer ID must be greater than 10 (customer.id> 10).One common check when creating apost_savesignal is to check is the instance is a new instance. This can be done by setting the parameter tocreatedand the comparison to "Is True".Our order model has acustomerfield which is a foreign key to thecustomermodel. We can traverse through thecustomerobject to get theidof the customer. We can then check ifcustomer.id > 10.The app has a handy autocomplete feature which will help you traverse through model fields and any cached properties. Don't worry about making any mistakes as there is validation in place to reject any parameters that can not be accessed.Saving this signal will now ensure that the signal will only be sent when the order is a new instance and the customer ID is greater than 10.InstallationTo install the application, run the following command:pip install django-email-signalsThe pip install command will be all that is required for most people, however if you want to look under the hood and see what's going on, you can clone the source directory:git clone https://github.com/Salaah01/django-email-signals.gitSetup1. Add toINSTALLED_APPSi. Add Addckeditorto yourINSTALLED_APPSin yoursettings.pyfile.INSTALLED_APPS=['app_1`,'app_2`,'...','ckeditor',]ii. Add Addemail_signalsto yourINSTALLED_APPSin yoursettings.pyfile. This should be added after any apps which contain models for which you would like to create signals using this application.INSTALLED_APPS=['app_1`,'app_2`,'...','ckeditor','email_signals`]2. Run Migrations and Collect Staticpython manage.py migrate
python manage.py collectstatic3. Update URLs (Option)Update your rooturls.pyfile to include the following:fromdjango.urlsimportincludeurl_patterns=[path('email-signals/',include('email_signals.urls')),]We recommend changing the URL to something a bit harder to guess, just to make life harder for those pesky snoopers. The application paths all require the user to be a staff member to be able to access the links.Though this step is optional, we recommend doing it as it will make setting constraints in the admin area much easier. The URLs are needed to provide a dropdown with options when building your constraints.4. Add a Default Email (Optional)AddEMAIL_SIGNAL_DEFAULT_SENDERto your settings.
e.g:EMAIL_SIGNAL_DEFAULT_SENDER = 'someone@mail.comIf you don't want to explicitly specify a sender email for every signal you define, you can setEMAIL_SIGNAL_DEFAULT_SENDERin your projectsettings.py.5. Add the Model MixinOn the models that you want to raise signals, you will need to add the following mixin as a dependency to the models:email_signals.models.EmailSignalMixin.Example:
Let's suppose you have the following model.fromdjango.dbimportmodelsclassCustomer(models.Model):name=models.CharField(max_length=200,null=True)email=models.CharField(max_length=200)You would need to change this model to the following:fromemail_signals.modelsimportEmailSignalMixinclassCustomer(models.Model,EmailSignalMixin):name=models.CharField(max_length=200,null=True)email=models.CharField(max_length=200)6. Add RecipientsDepending on the change to the data, you may want to send an email to different people. We facilitate this by setting up the various possible mailing lists into the model itself. This one is easier to show first then explain:fromemail_signals.modelsimportEmailSignalMixinclassCustomer(models.Model,EmailSignalMixin):name=models.CharField(max_length=200,null=True)email=models.CharField(max_length=200)defcustomer_emails(self):"""Recipient is the customer."""return[self.email]defmanagement_mailing_list(self):"""Recipient list includes management."""return['manager@somewhere.com','supervisor@somewhere.com']We've created two functions calledcustomer_emailsandmanagement_mailing_listwhich each return a collection of email addresses. Later on, when we setup the signals, we will be asked to set the mailing list to use for each signal. This is where we would enter our function names ``customer_emailsormanagement_mailing_list`.This therefore, allows us to set up different mailing lists within our models.Adding SignalsNow that the setup is complete, signals can be added via the admin (or by updating the database directly).We will imagine I am running a site on localhost and so the admin panel can be found by navigating tohttp://localhost:8000/admin/. The signals can then be accessed by navigating tohttp://localhost:8000/admin/email_signals/signal/. We will start by adding some signals. Click on "add signal" to get started.A wise man taught meit's better to sound silly for a moment than not know something and feel stupid forever. So, in that vein, though it might seem obvious, we'll go through the options in the form and discuss what each option
is responsible for.Field LabelField NameDescriptionNamenameAn name for your signal, just to make it easier to distinguish from other records.Descriptiondescription(Optional) Description for your signal.Model (Table)content_typeChoose from the drop down the model this signal relates to.Plain text contentplain_message(Optional) Plain text email to send.HTML contenthtml_message(Optional) HTML email to send.SubjectsubjectEmail subjectFrom emailfrom_email(Optional) The email sender. Defaults tosettings.EMAIL_SIGNAL_DEFAULT_SENDER.Mailing listmailing_listThe recipient list where the text you enter, corresponds to a method called in the model class with the same name. e.g: If you entercustomer_mails, then there will need to be a method calledcustomer_mailsthat returns a collection of emails in the model class. Alternatively, this can be a list of emails separated by a comma. e.g:test@email.com,test2@email.comwould send the email to both of these emails.Templatetemplate(Optional) Path to a template, should you wish to render an email from a template. This uses Django's template loader, so as the value you provide here should be relative tosettings.TEMPLATES[i]['DIRS'].Signal Typesignal_typeType of signal to raise for this record.ActiveactiveA switch to turn this signal on and off.Signal ConstraintsThis inline model is where you can set some constraints which will determine if the signal should be raised on a case by case basis.Field LabelField NameDescriptionParameter 1param_1The first parameter to use when testing a constraint. This parameter must exist in the signal kwargs or the model instance.ComparisoncomparisonDefine how to compare the parameters. E.g: parameter 1 isgreater thanparameter 2.Parameter 1param_1(Optional) The second parameter to use when testing a constraint. This parameter can be left empty when the constraint is something sensible. For example, if constraint is "Is True" then there is no need for parameter 2. But if the constraint is, "Greater Than", then parameter 2 is needed. Parameter 2 can also be a primitive type such as 'a', '1', '1.1'. The application will attempt to convert strings into numbers if it can.Parameters are DeepBoth parameters 1 and 2 allow you to search deep inside an object.
Let's suppose we have the following structure and signal has received aCustomerOrderinstance.classDiagram
    User <| -- Customer
    Customer <| -- CustomerOrder

    class User {
      id
      first_name
      last_name
      email
    }
    
    class Customer {
      id
      user
      fav_language
    }

    class CustomerOrder {
      id
      customer
      order_id
      total
    }Given aCustomerOrderinstance (we'll call this variableorder), we can set the following in our constraints:#Parameter 1ComparisonParameter 21'customer.user.id'Greater Than'5'2'customer.user.first_name'Equal To'customer.user.last_name'Constraint 1 will check the following:order.customer.user.id>5Similarly, constraint 2 will check the following:order.customer.user.first_name==order.customer.user.last_nameOnly when all constraints are satisfied will the email be sent.PlaygroundThe repository comes with an example project to get you started. If you prefer to test this application yourself then I recommend cloning the repository.Navigating toexampleand running the Django project inside.TestingIn the root of the project there is aruntests.pyfile which can be used to run the tests.