58 lines
1.5 KiB
Python
58 lines
1.5 KiB
Python
import random
|
|
import string
|
|
from django.utils.text import slugify
|
|
from django.core.mail import send_mail
|
|
from django.template.loader import render_to_string
|
|
from django.utils.html import strip_tags
|
|
from django.conf import settings
|
|
|
|
|
|
def send_email(user, subject, msg):
|
|
send_mail(
|
|
subject,
|
|
msg,
|
|
settings.EMAIL_FROM_ADDRESS,
|
|
[user.email],
|
|
fail_silently=False,
|
|
)
|
|
|
|
|
|
def send_html_email(subject, recipient_list, template, context):
|
|
"""A function responsible for sending HTML email"""
|
|
# Render the HTML template
|
|
html_message = render_to_string(template, context)
|
|
|
|
# Generate plain text version of the email (optional)
|
|
plain_message = strip_tags(html_message)
|
|
|
|
# Send the email
|
|
send_mail(
|
|
subject,
|
|
plain_message,
|
|
settings.EMAIL_FROM_ADDRESS,
|
|
recipient_list,
|
|
html_message=html_message,
|
|
)
|
|
|
|
|
|
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
|
|
return "".join(random.choice(chars) for _ in range(size))
|
|
|
|
|
|
def unique_slug_generator(instance, new_slug=None):
|
|
"""
|
|
Assumes the instance has a model with a slug field and a title
|
|
character (char) field.
|
|
"""
|
|
if new_slug is not None:
|
|
slug = new_slug
|
|
else:
|
|
slug = slugify(instance.title)
|
|
|
|
klass = instance.__class__
|
|
qs_exists = klass.objects.filter(slug=slug).exists()
|
|
if qs_exists:
|
|
new_slug = f"{slug}-{random_string_generator(size=4)}"
|
|
return unique_slug_generator(instance, new_slug=new_slug)
|
|
return slug
|