Package: baseapp-message-templates
BaseApp Message Templates - DjangoThis app provides the integration of custom e-mail and sms template configuration with The SilverLogic'sBaseApp.Install the packageAdd torequirements/base.txt:git+https://bitbucket.org/silverlogic/baseapp-message-templates-django.gitConfigure template settingsTEMPLATES=[{"BACKEND":"django_jinja.backend.Jinja2","DIRS":[str(APPS_DIR/"templates")],# change this to wherever your base templates are stored"APP_DIRS":True,"NAME":"jinja2","OPTIONS":{"match_extension":".j2","constants":{"URL":URL,"FRONT_URL":FRONT_URL},},},{"BACKEND":"django.template.backends.django.DjangoTemplates","DIRS":[str(APPS_DIR/"templates"),# change this to wherever your base templates are stored],"APP_DIRS":True,"OPTIONS":{"context_processors":["django.template.context_processors.debug","django.template.context_processors.request","django.contrib.auth.context_processors.auth","django.contrib.messages.context_processors.messages",],"libraries":{"filter":"baseapp_message_templates.filters",},},},]Default Email TemplateIn our Django application, you have the option to use a default email template. This template acts as a wrapper for your other email templates, ensuring a consistent layout and style across all your emails.Using the Default TemplateTo effectively utilize the default template:Create the Default TemplateEnsure your default template includes a placeholder for the child template content. This is done using thetemplate_content|safevariable in your Jinja2 template.Example:<html><body><div><!-- Your default template layout --><divclass="content">{{ template_content|safe }}</div><!-- More of your default template layout --></div></body></html>Render Child TemplatesWhen rendering a child template, pass the content as a string to template_content.Jinja2will insert this content into the default template at the location of {{ template_content|safe }}.Sanitize for Security:To ensure security, especially since we're using the safe filter, it's important to sanitizetemplate_contentto prevent XSS (Cross-Site Scripting) attacks. This process removes or neutralizes any potentially harmful scripts that might be part of the content.Setting Default Base Template (Optional)If you want to use a default base template that your emails will automatically inherit from, add the path to that template in your Django settings. This configuration allows you to define a consistent layout or design for your emails. Note that this base template won't apply to emails created directly in SendGrid.In yoursettings.py:DEFAULT_EMAIL_TEMPLATE="path/to/your/default/template"# ex: "emails/base-template"Setup SendGrid credentials (optional)If you want to use SendGrid to send mail, add these settings to yoursettings/base.py:DJMAIL_REAL_BACKEND="sendgrid_backend.SendgridBackend"SENDGRID_API_KEY=env("SENDGRID_API_KEY")SENDGRID_SANDBOX_MODE_IN_DEBUG=FalseEmailTemplate modelThis model is responsible for customizing your e-mail template and sending mail. At minimum, an instance ofEmailTemplatemust have a unique name and either a SendGrid template ID or some custom HTML content. Thesubject,plain_text_content, andattachmentsare optional.Static attachmentsAttachmentinstances that are linked to anEmailTemplaterepresent static files that will be attached to every message sent via that template, regardless of recipient or context. These attachments will be sent regardless of whether the e-mail is sent through a SendGrid template or a custom HTML template.Sending mail via SendGrid templateIf asendgrid_template_idis provided on an instance ofEmailTemplate, a SendGrid template can be used to send mail. In order to send mail via SendGrid template, at least onePersonalizationmust first be created. EachPersonalizationwill contain the email of a recipient and any context that must be provided to the template. APersonalizationcan be created like so:frombaseapp_message_templates.sendgridimportget_personalizationpersonalization=get_personalization("john@test.com",{"message":"Hello there."})Sending mail to one recipientThesend_via_sendgridmethod ofEmailTemplatecan be used to send a single email to one recipient. The method takes onePersonalizationas an argument, as well as an optional list ofattachmentsthat can be sent along with this particular message.frombaseapp_message_templates.modelsimportEmailTemplatefrombaseapp_message_templates.sendgridimportget_personalizationtemplate=EmailTemplate.objects.get("Test Template")personalization=get_personalization("john@test.com",{"message":"Hello there."})template.send_via_sendgrid(personalization)Sending mail to multiple recipientsThemass_send_via_sendgridmethod ofEmailTemplatecan be used to send multiple instances of a template to multiple recipients. The method takes a list ofPersonalizationobjects as an argument, and eachPersonalizationwill send a separate message to each recipient with its own context.frombaseapp_message_templates.modelsimportEmailTemplatefrombaseapp_message_templates.sendgridimportget_personalizationtemplate=EmailTemplate.objects.get("Test Template")personalization_1=get_personalization("john@test.com",{"message":"Hello there."})personalization_2=get_personalization("jane@test.com",{"message":"Good morning."})personalization_list=[personalization_1,personalization_2]template.mass_send_via_sendgrid(personalization_list)Sending Mail via custom HTMLIf you aren't using SendGrid and instead wish to provide your custom HTML content directly to theEmailTemplateinstance, this can be done through thehtml_contentfield. Oncehtml_contenthas been provided, thesendmethod of theEmailTemplatecan be used to send mail.Adding HTML content via Django AdminWhen adding HTML content to a template through the Django Admin, the "source" option must be selected in the text field.After saving, the content of the text field will no longer contain the raw HTML that was added. This is a small caveat of the Django Admin. The "raw HTML" field that is displayed underneath the input will display the actual raw HTML content that is currently added to the instance.SendingOnce you've addedhtml_contentto your template, either programatically or through the Django Admin, a message can now be sent through thesendmethod ofEmailTemplate.The only required parameter forsendisrecipients, which is a list of one or more strings containing the e-mail addresses of the recipients. Acontextdict can be passed in optionally if the HTML content is expected one or more key/value pairs to be provided.Theuse_base_templateflag will determine whether this message should extend from a base HTML template. If set toTrue, the message will extend from the base template that is located at a certain path. This path will either be the value ofextended_withif provided, or the value ofDEFAULT_EMAIL_TEMPLATE.Finally, theattachmentsparameter is a list of one or more files that will be send along with this particular message. These attachments will be sent along with any static attachments that have been attached to the template itself throughAttachment.frombaseapp_message_templates.modelsimportEmailTemplatetemplate=EmailTemplate.objects.get("Test Template")recipients=["john@test.com"]context={"content":"Hello."}extended_with="apps/base/templates/test-template.html"template.send(recipients,context,True,extended_with)SmsTemplate ModelTheSmsTemplatemodel has two fields:name: this name must be unique.message: this is a textfield and does not accept HTMLCreating migrations for your templateOnce you have installed the package you can simply create a migration to input your templates like so:from__future__importunicode_literalsfromdjango.dbimportmigrationsdefcreate_object(sms_template,name,message):sms_template.objects.create(name=name,message=message,)defcreate_sms_templates(apps,schema_migration):sms_template=apps.get_model("baseapp_message_templates","SmsTemplate")create_object(sms_template,"First Template","""Hello, {{ some_variable }}.""",)create_object(sms_template,"Second template","""Hello, {{ some_other_variable }}.""",)classMigration(migrations.Migration):dependencies=[("some_app","0002_some_previus_migration")]operations=[migrations.RunPython(create_sms_templates,migrations.RunPython.noop)]OBS: make sure that the variables are the right ones that you will pass as context when getting the message.Get the template messageTo get the template message you can simply use the util functionsget_sms_messagefromsms_utilspassing as first parameter the name of the template and the second parameter the context with your variables if needed.frombaseapp_message_templates.sms_utilsimportget_sms_messagecontext={"some_variable":"some_value"}message=get_sms_message("First Template",context)