hook mailchimp to contact forms
authorJan Szejko <janek37@gmail.com>
Fri, 6 Apr 2018 15:58:56 +0000 (17:58 +0200)
committerJan Szejko <janek37@gmail.com>
Fri, 6 Apr 2018 15:58:56 +0000 (17:58 +0200)
contact/forms.py
contact/mailing.py [new file with mode: 0644]
prawokultury/contact_forms.py
requirements.txt

index 419540a..132549e 100644 (file)
@@ -7,6 +7,8 @@ from django import forms
 from django.template.loader import render_to_string
 from django.template import RequestContext
 from django.utils.translation import ugettext_lazy as _
+
+from contact import mailing
 from .models import Attachment, Contact
 
 
@@ -35,6 +37,7 @@ class ContactForm(forms.Form):
     admin_list = None
     notify_on_register = True
     notify_user = True
+    mailing_field = None
 
     required_css_class = 'required'
     contact = forms.EmailField(label=_('E-mail'), max_length=128)
@@ -107,5 +110,7 @@ class ContactForm(forms.Form):
                     'no-reply@%s' % site.domain,
                     [contact.contact],
                     fail_silently=True)
+            if self.mailing_field and self.cleaned_data[self.mailing_field]:
+                mailing.subscribe(contact.contact)
 
         return contact
diff --git a/contact/mailing.py b/contact/mailing.py
new file mode 100644 (file)
index 0000000..bfd4209
--- /dev/null
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+
+from hashlib import md5
+
+import requests
+from django.conf import settings
+from mailchimp3 import MailChimp
+from mailchimp3.mailchimpclient import MailChimpError
+
+INTERESTS = {settings.MAILCHIMP_GROUP_ID: True}
+
+
+def get_client():
+    headers = requests.utils.default_headers()
+    headers['User-Agent'] = '%s (%s)' % settings.MANAGERS[0]
+
+
+def subscriber_hash(email):
+    return md5(email).hexdigest()
+
+
+def remove_from_groups(email, client):
+    group_ids = []
+    categories = client.lists.interest_categories.all(list_id=settings.MAILCHIMP_LIST_ID)['categories']
+    for category in categories:
+        groups = client.lists.interest_categories.interests.all(
+            list_id=settings.MAILCHIMP_LIST_ID, category_id=category['id'])['interests']
+        group_ids += [group['id'] for group in groups]
+    interests = {group_id: False for group_id in group_ids}
+    client.lists.members.update(
+         settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
+         data={'interests': interests})
+
+
+def subscribe(email):
+    client = MailChimp(mc_api=settings.MAILCHIMP_API_KEY, timeout=10.0)
+    try:
+        member = client.lists.members.get(settings.MAILCHIMP_LIST_ID, subscriber_hash(email))
+    except MailChimpError:
+        pass
+    else:
+        if member['status'] != 'subscribed':
+            remove_from_groups(email, client)
+    client.lists.members.create_or_update(
+        settings.MAILCHIMP_LIST_ID, subscriber_hash(email),
+        data={
+            'email_address': email,
+            'status_if_new': 'subscribed',
+            'status': 'subscribed',
+            'interests': INTERESTS,
+        }
+    )
index 6fc165e..81c2a0d 100644 (file)
@@ -28,6 +28,8 @@ class RegistrationForm(ContactForm):
     form_title = _('Registration')
     admin_list = ['first_name', 'last_name', 'organization']
 
+    mailing_field = 'agree_mailing'
+
     travel_grant_countries = TRAVEL_GRANT_COUNTRIES
 
     first_name = forms.CharField(label=_('First name'), max_length=128)
@@ -129,11 +131,17 @@ class RegistrationForm(ContactForm):
     )
     agree_data = forms.BooleanField(
         label=_('Permission for data processing'),
-        help_text=_(u'I hereby grant Modern Poland Foundation (Fundacja Nowoczesna Polska, ul. MarszaƂkowska 84/92, 00-514 Warszawa) permission to process my personal data (name, e-mail address) for purposes of registration for CopyCamp conference.')
+        help_text=_(
+            u'I hereby grant Modern Poland Foundation (Fundacja Nowoczesna Polska, ul. MarszaƂkowska 84/92, '
+            u'00-514 Warszawa) permission to process my personal data (name, e-mail address) for purposes '
+            u'of registration for CopyCamp conference.')
     )
     agree_license = forms.BooleanField(
         label=_('Permission for publication'),
-        help_text=mark_safe_lazy(_(u'I agree to having materials, recorded during the conference, released under the terms of <a href="http://creativecommons.org/licenses/by-sa/3.0/deed">CC\u00a0BY-SA</a> license and to publishing my image.')),
+        help_text=mark_safe_lazy(_(
+            u'I agree to having materials, recorded during the conference, released under the terms of '
+            u'<a href="http://creativecommons.org/licenses/by-sa/3.0/deed">CC\u00a0BY-SA</a> license and '
+            u'to publishing my image.')),
         required=False
     )
 
@@ -212,25 +220,30 @@ class RegisterSpeaker(RegistrationForm):
     save_as_tag = '2017-speaker'
     form_title = _('Open call for presentations')
     notify_on_register = False
+    mailing_field = 'agree_mailing'
 
     # inherited fields included so they are not translated
     first_name = forms.CharField(label=_('First name'), max_length=128)
     last_name = forms.CharField(label=_('Last name'), max_length=128)
-    organization = forms.CharField(label=_('Organization'),
-            max_length=256, required=False)
+    organization = forms.CharField(label=_('Organization'), max_length=256, required=False)
     agree_mailing = forms.BooleanField(
         label=_('I am interested in receiving information about the Modern Poland Foundation\'s activities by e-mail'),
         required=False
     )
     agree_license = forms.BooleanField(
         label=_('Permission for publication'),
-        help_text=mark_safe_lazy(_(u'I agree to having materials, recorded during the conference, released under the terms of <a href="http://creativecommons.org/licenses/by-sa/3.0/deed">CC\u00a0BY-SA</a> license and to publishing my image.')),
+        help_text=mark_safe_lazy(_(
+            u'I agree to having materials, recorded during the conference, released under the terms of '
+            u'<a href="http://creativecommons.org/licenses/by-sa/3.0/deed">CC\u00a0BY-SA</a> license and '
+            u'to publishing my image.')),
         required=False
     )
 
     presentation_thematic_track = forms.ChoiceField(
         label=_('Please select one thematic track'),
-        choices=[(t, mark_safe('<strong>%s</strong><p style="margin-left: 20px;">%s</p>' % (t, desc))) for t, desc in tracks],
+        choices=[
+            (t, mark_safe('<strong>%s</strong><p style="margin-left: 20px;">%s</p>' % (t, desc)))
+            for t, desc in tracks],
         widget=forms.RadioSelect())
 
     bio = forms.CharField(label=_('Short biographical note in English (max. 500 characters)'), widget=forms.Textarea,
@@ -319,6 +332,7 @@ class WorkshopForm(ContactForm):
     conference_name = u'CopyCamp 2017'
     form_title = _('Workshop')
     notify_on_register = False
+    mailing_field = 'agree_mailing'
 
     first_name = forms.CharField(label=_('First name'), max_length=128)
     last_name = forms.CharField(label=_('Last name'), max_length=128)
index db9fae8..c2c3916 100644 (file)
@@ -28,3 +28,5 @@ pysolr
 django-piwik
 
 django-sponsors>=1.2.1,<2.0
+
+mailchimp3
\ No newline at end of file