I have just integrated Mailchimp to my Django Project using Ajax. The email address field is working properly and I'm able to get the email in both my Mailchimp list and my database. Now when I try to add a field that let a user add his first name to the form, I keep getting errors like this one for example: from .utils import SendSubscribeMail
File "C:\Users\locq\Desktop\Coding\SEARCH_APP\venv\src\search\utils.py", line 8
self.fname = fname
^
TabError: inconsistent use of tabs and spaces in indentation..
So how can I add a FNAME field and send the datas to mailchimp on submit?
Here's my code:
In my Settings.p I added my Mailchimp credentials at the bottom like this:
MAILCHIMP_API_KEY = '767ba************-us6'
MAILCHIMP_SUBSCRIBE_LIST_ID = '45c*******'
I created a utils.py file to use Threading, the Mailchimp package and import my credentials from the settings:
import threading
import mailchimp
from django.conf import settings
class SendSubscribeMail(object):
def __init__(self, email, fname):
self.email = email
self.fname = fname
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
API_KEY = settings.MAILCHIMP_API_KEY
LIST_ID = settings.MAILCHIMP_SUBSCRIBE_LIST_ID
api = mailchimp.Mailchimp(API_KEY)
try:
api.lists.subscribe(LIST_ID, {'email': self.email}, merge_vars={'FNAME': self.fname}, double_optin=False)
except:
return False
Custom Def to get the input names:
def subscribe(request):
if request.method == 'POST':
fname = request.POST['fname_id']
Subscribe.objects.create(fname_id = fname)
email = request.POST['email_id']
email_qs = Subscribe.objects.filter(email_id = email)
if email_qs.exists():
data = {"status" : "404"}
return JsonResponse(data)
else:
Subscribe.objects.create(email_id = email)
SendSubscribeMail(email, fname) # Send the Mail, Class available in utils.py
return HttpResponse("/")
The models.py I use to add the email (and fname) in the Subscribe table of my database:
class Subscribe(models.Model):
email_id = models.EmailField()
fname_id = models.CharField(max_length=255, blank=True, null=True, default='')
timestamp = models.DateTimeField(auto_now=True)
def __str__(self):
return self.email_id
My html form:
<div class="signup subs-form">
<div class="header">
<p>Sign Up For Beta</p>
</div>
<div class="description">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna.</p>
</div>
<form method="POST" id="subscribe" class="subs-form">
{% csrf_token %}
<div>
<input type="email" class="button-" id="email" name="email_id" placeholder="E-mail">
<div class="input">
<input type="text" class="button-" id="fname" name="fname_id" placeholder="First Name">
<input type="submit" class="button-" id="submit" value="Join">
</div>
</div>
</form>
</div>
And finally, here's the Ajax code I have at the bottom of my page:
$('#subscribe').submit(function(e){
e.preventDefault();
var email_id = $("#email").val();
if(email_id){
var csrfmiddlewaretoken = csrftoken;
var fname_id = $("#fname").val();
var email_data = {"email_id": email_id,
"fname_id": fname_id,
"csrfmiddlewaretoken" : csrfmiddlewaretoken};
$.ajax({
type : 'POST',
url : '/subscribe/',
data : email_data,
success : function(response){
$('#email').val('');
if(response.status == "404"){
alert("This Email is already been subscribed!");
}
else{
alert("Thank you for Subscribing! Please Check your Email to Confirm the Subscription");
}
},
error: function(response) {
alert("Sorry Something went Wrong");
$('#email').val('');
}
});
return false;
}
else{
alert("Please provide correct email!");
}
});
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
})
How can I achieve this?