aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthew Lemon <y@yulqen.org>2024-12-08 15:30:51 +0000
committerMatthew Lemon <y@yulqen.org>2024-12-08 15:30:51 +0000
commit9950234b1aa07fceed0d220297d158be6a067cd2 (patch)
tree23708f889cfc11f84dbc288508a29719a18ac53d
parent30101453a75aaa635e3458d509dec164a6a68ac1 (diff)
wip: sorting out the email sending
-rw-r--r--alphabetlearning/payments/admin.py7
-rw-r--r--alphabetlearning/payments/forms.py6
-rw-r--r--alphabetlearning/payments/models.py2
-rw-r--r--alphabetlearning/payments/urls.py14
-rw-r--r--alphabetlearning/payments/views.py99
-rw-r--r--alphabetlearning/resources/models.py4
-rw-r--r--config/settings/local.py16
7 files changed, 91 insertions, 57 deletions
diff --git a/alphabetlearning/payments/admin.py b/alphabetlearning/payments/admin.py
index 156baf3..fc0db91 100644
--- a/alphabetlearning/payments/admin.py
+++ b/alphabetlearning/payments/admin.py
@@ -17,6 +17,7 @@ from .models import Subscription
class SuccessEmailSignupAdmin(admin.ModelAdmin):
list_display = ("email", "date_added")
+
class SubscriptionPlanAdmin(admin.ModelAdmin):
list_display = ("name", "price", "description", "allowed_downloads")
@@ -26,8 +27,10 @@ class CartItemAdminInline(admin.TabularInline):
class ShoppingCartAdmin(admin.ModelAdmin):
-# list_display = ("user", "created_at", "updated_at")
- inlines = [CartItemAdminInline,]
+ # list_display = ("user", "created_at", "updated_at")
+ inlines = [
+ CartItemAdminInline,
+ ]
# class CartItemAdmin(admin.ModelAdmin):
diff --git a/alphabetlearning/payments/forms.py b/alphabetlearning/payments/forms.py
index f69397f..3aa2d95 100644
--- a/alphabetlearning/payments/forms.py
+++ b/alphabetlearning/payments/forms.py
@@ -5,10 +5,10 @@ from .models import EmailVerification
class EmailVerificationForm(forms.ModelForm):
class Meta:
model = EmailVerification
- fields = ['email']
+ fields = ["email"]
def clean_email(self):
- email = self.cleaned_data.get('email')
+ email = self.cleaned_data.get("email")
if EmailVerification.objects.filter(email=email).exists():
raise forms.ValidationError("This email address is already in use.")
- return email \ No newline at end of file
+ return email
diff --git a/alphabetlearning/payments/models.py b/alphabetlearning/payments/models.py
index 3a3ba10..44c8597 100644
--- a/alphabetlearning/payments/models.py
+++ b/alphabetlearning/payments/models.py
@@ -23,6 +23,7 @@ class EmailVerification(models.Model):
def __str__(self):
return f"Email verification for {self.email}"
+
class EmailSignup(models.Model):
email = models.EmailField(unique=True)
date_added = models.DateTimeField(auto_now_add=True)
@@ -30,6 +31,7 @@ class EmailSignup(models.Model):
def __str__(self):
return self.email
+
class Product(models.Model):
name = models.CharField(max_length=255)
stripe_product_id = models.CharField(max_length=100)
diff --git a/alphabetlearning/payments/urls.py b/alphabetlearning/payments/urls.py
index 38393e0..d422b8f 100644
--- a/alphabetlearning/payments/urls.py
+++ b/alphabetlearning/payments/urls.py
@@ -19,11 +19,17 @@ urlpatterns = [
),
path("add-to-basket/<int:resource_id>", views.add_to_cart, name="add_to_basket"),
path("landing/", views.ProductLandingPageView.as_view(), name="landing"),
- path("delete-cart-item/<int:pk>", views. DeleteCartItem.as_view(), name="delete_cart_item"),
+ path("delete-cart-item/<int:pk>", views.DeleteCartItem.as_view(), name="delete_cart_item"),
path("webhooks/stripe/", views.stripe_webhook, name="stripe-webhook"),
# path("email_signup/", views.email_signup, name="email_signup"),
- path("email-sign-up-verification/", views.email_signup_verification, name="email_signup_verification"),
+ path(
+ "email-sign-up-verification/",
+ views.email_signup_verification,
+ name="email_signup_verification",
+ ),
path("verify-email/<str:token>/", views.verify_email, name="verify_email"),
- path("success_email_signup/", views.SuccessEmailSignupView.as_view(), name="success_email_signup"),
- path('privacy-policy/', privacy_policy, name='privacy_policy'), # Add this line
+ path(
+ "success_email_signup/", views.SuccessEmailSignupView.as_view(), name="success_email_signup"
+ ),
+ path("privacy-policy/", privacy_policy, name="privacy_policy"), # Add this line
]
diff --git a/alphabetlearning/payments/views.py b/alphabetlearning/payments/views.py
index dda7900..6290e08 100644
--- a/alphabetlearning/payments/views.py
+++ b/alphabetlearning/payments/views.py
@@ -1,3 +1,4 @@
+import requests
import stripe
from django.conf import settings
from django.contrib.auth.decorators import login_required
@@ -63,52 +64,77 @@ def email_signup_verification(request):
email=form.cleaned_data.get("email"),
)
# Generate verification URL
- verification_url:str = request.build_absolute_uri(
- reverse('payments:verify_email', args=[str(pending_verification.verification_token)])
+ verification_url: str = request.build_absolute_uri(
+ reverse(
+ "payments:verify_email", args=[str(pending_verification.verification_token)]
+ )
)
- email = process_verification_emails(verification_url, form.cleaned_data.get("email"), pending_verification, request)
- return render(request, 'payments/verification_sent.html', {
- 'email': email
- })
+ email = process_verification_emails(
+ email=form.cleaned_data.get("email"),
+ verification_url=verification_url,
+ )
+ # email = send_mailgun_verification(
+ # form.cleaned_data.get("email"), verification_url, pending_verification
+ # )
+ return render(request, "payments/verification_sent.html", {"email": email})
else:
- email = process_verification_emails(request.POST.get("email"), warn=True)
- return render(request, 'payments/verification_sent.html', {
- 'email': email
- })
+ email = process_verification_emails(email=request.POST.get("email"), warn=True)
+ return render(request, "payments/verification_sent.html", {"email": email})
else:
form = EmailVerificationForm()
return render(request, "pages/home.html", {"form": form}) # Adjust as necessary
-def process_verification_emails(email: str, verification_url: str=False, email_verification_obj: EmailVerification=False, warn=False):
+def send_mailgun_verification(
+ email: str,
+ verification_url: str,
+ email_verification_obj: EmailVerification = False,
+ warn=False,
+):
+ requests.post(
+ "https://api.mailgun.net/v3/sandbox98fd3a1c6501446aa57a9c8b76e56e15.mailgun.org/messages",
+ auth=("api", "7535a010b822cd503dc5a11670a64194-f55d7446-76d3865a"),
+ data={
+ "from": "Excited User <mailgun@sandbox98fd3a1c6501446aa57a9c8b76e56e15.mailgun.org>",
+ "to": [email, email],
+ "subject": "Hello - Test from Mailgun",
+ "text": f"Thanks, {email} for signing up.\n\nTesting some Mailgun awesomeness",
+ },
+ )
+ return email
+
+def process_verification_emails(
+ email: str,
+ verification_url: str = None,
+ warn=False,
+):
if warn is False:
- html_warning_message = f'''
+ html_warning_message = f"""
<p>Please click the following link to verify your email address within 24 hours:</p>
<p><a href="{verification_url}">{verification_url}</a></p>
<p>If you didn't request this, please ignore this email.</p>
- '''
- warning_message = f'''
+ """
+ warning_message = f"""
Please click the following link to verify your email address within 24 hours:
{verification_url}
If you didn't request this, please ignore this email.
- '''
+ """
admin_warn = "They are not already subscribed."
else:
- html_warning_message = f'''
+ html_warning_message = """
<p>You are already subscribed to our list - no further action is required.</p>
- '''
- warning_message = '''
+ """
+ warning_message = """
You are already subscribed to our list - no further action is required.
- '''
+ """
admin_warn = "They have already subscribed so have been told of this fact in their verification email. No further action required."
# Send verification email
- subject = 'Alphabet Learning - Email Verification'
- html_message = f'''
+ subject = "Alphabet Learning - Email Verification"
+ html_message = f"""
<html>
<body>
- <img src="http://localhost:8000/static/images/AL_long_logo_black_grey.png" alt="Alphabet Learning Logo" style="max-width: 200px; margin-bottom: 20px;">
<p>Hi!</p>
<p>You recently requested to sign up to the Alphabet Learning contact list.</p>
{html_warning_message}
@@ -116,8 +142,8 @@ def process_verification_emails(email: str, verification_url: str=False, email_v
<p>The Alphabet Learning Team</p>
</body>
</html>
- '''
- message = f'''
+ """
+ message = f"""
Hi!,
You recently requested to sign up to the Alphabet Learning contact list.
@@ -126,16 +152,16 @@ def process_verification_emails(email: str, verification_url: str=False, email_v
Best regards,
The Alphabet Learning Team
- '''
+ """
send_mail(
subject,
message,
settings.DEFAULT_FROM_EMAIL,
[email],
fail_silently=False,
- html_message=html_message
+ html_message=html_message,
)
- admin_message = f'''
+ admin_message = f"""
Joanna/Matthew,
{email} has just signed up to the Alphabet Learning contact list. They are awaiting verification.
@@ -146,20 +172,17 @@ def process_verification_emails(email: str, verification_url: str=False, email_v
Best regards,
The Alphabet Learning Server
- '''
+ """
mail_admins(subject, admin_message, fail_silently=False)
return email
def verify_email(request, token):
try:
- pending = EmailVerification.objects.get(
- verification_token=token,
- is_verified=False
- )
+ pending = EmailVerification.objects.get(verification_token=token, is_verified=False)
if pending.is_expired:
- return render(request, 'payments/verification_failed.html')
+ return render(request, "payments/verification_failed.html")
# Create the subscriber
EmailSignup.objects.create(
@@ -171,16 +194,16 @@ def verify_email(request, token):
pending.save()
mail_admins(
- subject=f'{pending.email} has just signed up to the Alphabet Learning contact list.',
- message=f'{pending.email} has just signed up to the Alphabet Learning contact list. Their verification was successful.\n\n\n'
- f'Best regards,\n\nThe Alphabet Learning Server',
+ subject=f"{pending.email} has just signed up to the Alphabet Learning contact list.",
+ message=f"{pending.email} has just signed up to the Alphabet Learning contact list. Their verification was successful.\n\n\n"
+ f"Best regards,\n\nThe Alphabet Learning Server",
fail_silently=False,
)
- return render(request, 'payments/success_email_signup.html')
+ return render(request, "payments/success_email_signup.html")
except EmailVerification.DoesNotExist:
- return render(request, 'payments/verification_failed.html')
+ return render(request, "payments/verification_failed.html")
def create_line_items(resources):
diff --git a/alphabetlearning/resources/models.py b/alphabetlearning/resources/models.py
index ebdf98d..6881483 100644
--- a/alphabetlearning/resources/models.py
+++ b/alphabetlearning/resources/models.py
@@ -38,13 +38,13 @@ DESC_HELP_TEXT = """
class Resource(models.Model):
name = models.CharField(max_length=255, null=False)
stripe_product_id = models.CharField(max_length=100)
- #price = models.DecimalField(
+ # price = models.DecimalField(
# max_digits=6,
# decimal_places=2,
# default=0.00,
# null=False,
# blank=False,
- #)
+ # )
thumbnail_filenames = models.JSONField(
null=False,
verbose_name="Thumbnail filenames",
diff --git a/config/settings/local.py b/config/settings/local.py
index 0e4b7e4..b9eb50b 100644
--- a/config/settings/local.py
+++ b/config/settings/local.py
@@ -38,24 +38,24 @@ DEFAULT_FROM_EMAIL = env(
default="alphabetlearning.online <help@alphabetlearning.online>",
)
SERVER_EMAIL = env("DJANGO_SERVER_EMAIL", default=DEFAULT_FROM_EMAIL)
-EMAIL_HOST = env('EMAIL_HOST')
-EMAIL_PORT = env('EMAIL_PORT')
-EMAIL_HOST_USER = env('EMAIL_HOST_USER')
-EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
-EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', default=True)
+EMAIL_HOST = env("EMAIL_HOST")
+EMAIL_PORT = env("EMAIL_PORT")
+EMAIL_HOST_USER = env("EMAIL_HOST_USER")
+EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD")
+EMAIL_USE_TLS = env.bool("EMAIL_USE_TLS", default=True)
# WhiteNoise
# ------------------------------------------------------------------------------
# http://whitenoise.evans.io/en/latest/django.html#using-whitenoise-in-development
-#INSTALLED_APPS = ["whitenoise.runserver_nostatic", *INSTALLED_APPS]
+# INSTALLED_APPS = ["whitenoise.runserver_nostatic", *INSTALLED_APPS]
# django-debug-toolbar
# ------------------------------------------------------------------------------
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#prerequisites
-#INSTALLED_APPS += ["debug_toolbar"]
+# INSTALLED_APPS += ["debug_toolbar"]
# https://django-debug-toolbar.readthedocs.io/en/latest/installation.html#middleware
-#MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
+# MIDDLEWARE += ["debug_toolbar.middleware.DebugToolbarMiddleware"]
# https://django-debug-toolbar.readthedocs.io/en/latest/configuration.html#debug-toolbar-config
# DEBUG_TOOLBAR_CONFIG = {
# # "DISABLE_PANELS": ["debug_toolbar.panels.redirects.RedirectsPanel"],